简体   繁体   中英

Is it possible to use Newtonsoft.Json when using HttpClient.PostAsJsonAsync(something)?

Let's say I want to add a typed HttpClient like this:

services.AddHttpClient<ISomeService, SomeService>(c =>
{
    c.BaseAddress = new Uri(someUrl);
});

Is it possible to force it to use Newtonsoft.Json for serialization when sending requests? Preferably in a similar fashion how it can be added for controllers:

services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });

So that when I use HttpClient instance like that: await httpClient.PostAsJsonAsync(testDto) , Newtonsoft.Json serializer is used instead of the built-in one.

EDIT: Just noticed that PostAsJsonAsync(...) and GetFromJsonAsync(...) I am using are extension methods defined in System.Net.Http.Json , which basically renders this whole question invalid.

If you want to use Newtonsoft.Json , use the System.Net.Http.HttpClientExtensions namespace .

If you want to use the new System.Text.Json , use the System.Net.Http.Json.HttpClientJsonExtensions namespace .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM