Notification texts go here Contact Us Buy Now!

Set system.text.json.jsonserializer globally minimal api

ConfigureHttpJsonOptions and AddJsonOptions manage serilizer settings for model binding/response serialization, they will not affect the settings you use to deserialize manually. Provide settings for JsonSerializer.Deserialize, for example:

var res = JsonSerializer.Deserialize<WeatherForecast[]>(responseContent, 
    new JsonSerializerOptions
    {
        PropertyNameCaseInsensitive = true
    });
Notes
  1. There is no need to explicitly configure JSON options for API to only set the PropertyNameCaseInsensitive to true since JsonSerializerDefaults.Web defaults to PropertyNameCaseInsensitive = true:

    The following options have different defaults for web apps:

    • PropertyNameCaseInsensitive = true
    • JsonNamingPolicy = CamelCase
    • NumberHandling = AllowReadingFromString
  2. You can resolve configured JSON options from the DI. For example for minimal APIs (or you can configure your own and resolve them):

    app.MapGet("/weatherforecast", (IOptions<Microsoft.AspNetCore.Http.Json.JsonOptions> opts) =>
         {
             var serOpts = opts.Value.SerializerOptions;
             // ...
         });
    
    
  3. You should not need to deserialize data to just serialize it back again (in the shown code at least). Returning content should do the trick: return Results.Content(responseContent, "application/json");

  4. You can't mutate default serialization options (see this github comment for example), at least ATM, but you can define helper/extension methods which will use some global statically defined ones.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.