skip to Main Content

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


  1. You could try create an extension class for httpclient, then all httpclient GetFromJsonAsync will apply this options.

        public static class HttpClientExtensions
        {
            public static async Task<T> GetFromJsonAsync<T>(this HttpClient httpClient, string requestUri)
            {
                var jsonSerializerOptions = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true,
                };
                jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
    
                var response = await httpClient.GetStringAsync(requestUri);
                return JsonSerializer.Deserialize<T>(response, jsonSerializerOptions);
            }
        }
    
    Login or Signup to reply.
  2. Here is below the correct way to configure HttpClient only once and globally.

    builder.Services.AddHttpClient()
        .ConfigureHttpJsonOptions(opt =>
        {
            opt.SerializerOptions.PropertyNameCaseInsensitive = true;
            opt.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
        });
    

    You should be using the extension methods exposed by AddHttpClient() Please let me know if it works for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search