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.
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
);
}
}