Access JsonOptions from a middleware in ASP.NET Web Api

Viewed 842

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?

1 Answers

The problem was quite tricky. There are two namespaces containing a JsonOptions class:

  1. Microsoft.AspNetCore.Mvc
  2. Microsoft.AspNetCore.Http.Json

Using the first one resolved my problem. Internally these two classes are very similar and I didn't pay attention for the corresponding namespace during the middleware implementation.

Related