从 ASP.NET Web Api 中的中间件访问 JsonOptions

sha*_*are 6 .net c# serialization json asp.net-web-api

在 ASP.NET Web API 项目中,我有一个自定义 json 转换器。它在使用典型 API 控制器方法的场景中工作得非常好。但不知何故,我无法从在标准 Web API 管道之外工作的中间件访问配置的 JsonOptions。

一个简单的中间件来重现问题:

    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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

以及配置片段:

        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(); });
        }
Run Code Online (Sandbox Code Playgroud)

当 http 请求命中时,中间件IOptions<JsonOptions> jsonOptions有一个 SerializerOptions 对象,该对象不包含我在配置中设置的转换器。

有没有办法使用正确配置的 SerializerOptions 来访问实际的 JsonOptions ?

sha*_*are 6

问题相当棘手。有两个包含JsonOptions类的命名空间:

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

使用第一个解决了我的问题。从内部来看,这两个类非常相似,在中间件实现过程中我没有关注相应的命名空间。