In my ASP.NET web API I have httpClient
which call GetFromJsonAsync
:
var jsonSerializerOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
await httpClient.GetFromJsonAsync<Item[]>(uri, jsonSerializerOptions);
It is quite repetitive to add the jsonSerializerOptions parameter in all my GetFromJsonAsync calls even if I inject it.
// I tried this without success
builder.Services
.ConfigureHttpJsonOptions(x => x.SerializerOptions.Converters.Add(new JsonStringEnumConverter()))
.Configure<JsonSerializerOptions>(x => x.Converters.Add(new JsonStringEnumConverter()))
.AddJsonOptions(x => x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
// no need to specify the jsonSerializerOptions because it should be configured for this httpClient
await httpClient.GetFromJsonAsync<Item[]>(uri);
Is there a way to configure it per httpClient once for all?
2
Answers
You could try create an extension class for httpclient, then all httpclient
GetFromJsonAsync
will apply this options.Here is below the correct way to configure
HttpClient
only once and globally.You should be using the extension methods exposed by
AddHttpClient()
Please let me know if it works for you.