79250616

Date: 2024-12-04 09:56:22
Score: 0.5
Natty:
Report link

Based on @Elijah's suggestion about registering IOptions, here's a complete solution that shows how to properly configure and use JSON serialization options globally.

Solution

First, configure the options in Program.cs:

    services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
    {
       options.SerializerOptions.PropertyNameCaseInsensitive = true;
       options.SerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString;
       options.SerializerOptions.WriteIndented = false;
       options.SerializerOptions.MaxDepth = 18;
       options.SerializerOptions.AllowTrailingCommas = true;
       options.SerializerOptions.ReadCommentHandling = JsonCommentHandling.Skip;
    });

Then inject and use these options in your services.If you need you can ovveride in constructor.:

public class TestService : ITestService
{
   private readonly JsonSerializerOptions _jsonSerializerOptions;

   public TestService(IOptions<JsonOptions> jsonOptions)
   {
       _jsonSerializerOptions = jsonOptions.Value.SerializerOptions;
   }

   public async Task<ModelDto> DeserializeObjectAsync(MemoryStream ms)
   {
       return await JsonSerializer.DeserializeAsync<ModelDto>(
           ms, 
           _jsonSerializerOptions
       );
   }
}
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Elijah's
  • Low reputation (1):
Posted by: capslo