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

Ram*_*yev 9 c# system.text.json asp.net-core-3.1

我使用 System.Text.Json 并在 Startup.cs 的 ConfigureServices 方法中设置 JsonSerializerOptions

 public void ConfigureServices(IServiceCollection services)
 { 
 ...
            services.AddControllers()
                    .AddJsonOptions(options =>
                    {
                        options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                    });
 ...
 }
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能实现这个目标?谢谢。

wei*_*hch 12

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

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

    await _next(httpContext);
}
Run Code Online (Sandbox Code Playgroud)

  • 附加说明:它必须是 Microsoft.AspNetCore.Mvc.JsonOptions。因为还存在 Microsoft.AspNetCore.Http.Json.JsonOptions (2认同)