In a ASP.NET Web API project I have a custom json converter. It works perfectly fine in a scenario with a typical API controller methods. But somehow I can not access the configured JsonOptions from a middleware which works outside the standard Web API pipeline.
A simple middleware to reproduce the problem:
public sealed class TestMiddleware
{
public async Task Invoke(HttpContext httpContext, IOptions<JsonOptions> jsonOptions)
{
// Some logic to check the middleware must be applied
// ...
// Return a response
await httpContext.Response.WriteAsJsonAsync(data, jsonOptions.Value.SerializerOptions);
}
}
And the configuration fragment:
public void ConfigureServices(IServiceCollection services)
{
services
.AddControllers()
.AddJsonOptions(configure =>
{
configure.JsonSerializerOptions.Converters.Add(new MyCustomConverter());
configure.JsonSerializerOptions.IgnoreNullValues = true;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseMiddleware<TestMiddlewre>();
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
When a http request hits the middleware IOptions<JsonOptions> jsonOptions has a SerializerOptions object which doesn't contain converters that I have setup in the configuration.
Is there a way to access the actual JsonOptions with the proper configured SerializerOptions?