如何在ASP.NET Core 3.1中获取当前的JsonSerializerOptions?

8
我使用System.Text.Json,并在Startup.cs的ConfigureServices方法中设置了JsonSerializerOptions。
 public void ConfigureServices(IServiceCollection services)
 { 
 ...
            services.AddControllers()
                    .AddJsonOptions(options =>
                    {
                        options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                    });
 ...
 }

现在我想在CustomErrorHandlingMiddleware中获取当前的JsonSerializerOptions。

public async Task InvokeAsync(HttpContext context)
{
      try
      {
          await _next(context);
      }
      catch (Exception exc)
      {
          var response = new SomeObject(); 
                
          var currentJsonSerializerOptions = ? //I want get CurrentJsonSerializerOptions here

          var result = System.Text.Json.JsonSerializer.Serialize(response, currentJsonSerializerOptions);

          context.Response.ContentType = "application/json";
          context.Response.StatusCode = 500;
          await context.Response.WriteAsync(result);
      }
}

我该如何实现这个?谢谢。

2个回答

12

根据选项模式,您可以注入IOptions<JsonOptions>IOptionsSnapshot<JsonOptions>到您的中间件中。

public async Task Invoke(HttpContext httpContext, IOptions<JsonOptions> options)
{
    JsonSerializerOptions serializerOptions = options.Value.JsonSerializerOptions;

    await _next(httpContext);
}

嗨,朋友。感谢你的回答。我尝试了这个解决方案,但是注入的IOptions<JsonSerializerOptions>或IOptionsSnapshot<JsonSerializerOptions>的值与我在Startup.cs中设置的值不同。例如,我设置了"JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase",但是当注入IOptions<JsonSerializerOptions>(或IOptionsSnapshot<JsonSerializerOptions>)时,PropertyNamingPolicy的值为null。 - Ramil Aliyev 007
1
@RamilAliyev 抱歉,我类型写错了,请尝试更新。 - weichch
2
附加说明:它必须是 Microsoft.AspNetCore.Mvc.JsonOptions。因为还存在 Microsoft.AspNetCore.Http.Json.JsonOptions。 - sepulka
@sepulka 对我来说两者都可以。你知道它们之间的区别吗? - Zero3
@Zero3,第一个是为Newtonsoft Json而准备的,第二个是为System.Text.Json而准备的。不同的库有不同的类,但功能相同。 - sepulka
显示剩余2条评论

1

您可以编写一个中间件类,该类继承自ActionResult,如下所示:

public override Task ExecuteResultAsync(ActionContext context)
        {
            var httpContext = context.HttpContext;
            var response    = httpContext.Response;
            response.ContentType = "application/json; charset=utf-8";
            response.StatusCode  = (int) _statusCode;

            var options = httpContext.RequestServices.GetRequiredService<IOptions<JsonOptions>>().Value;

            return JsonSerializer.SerializeAsync(response.Body, _result, _result.GetType(), options.JsonSerializerOptions);
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接