简体   繁体   English

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

[英]How to get current JsonSerializerOptions in ASP.NET Core 3.1?

I use System.Text.Json and I set JsonSerializerOptions in ConfigureServices method of Startup.cs我使用 System.Text.Json 并在 Startup.cs 的 ConfigureServices 方法中设置 JsonSerializerOptions

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

Now I want get current JsonSerializerOptions in CustomErrorHandlingMiddleware现在我想在 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);
      }
}

How can I achieve this?我怎样才能做到这一点? Thanks.谢谢。

You could inject IOptions<JsonOptions> or IOptionsSnapshot<JsonOptions> as per Options pattern into your middleware.您可以根据Options 模式IOptions<JsonOptions>IOptionsSnapshot<JsonOptions>注入到中间件中。

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

    await _next(httpContext);
}

You can write a middleware class that inherits from ActionResult as follows您可以编写一个继承自ActionResult的中间件 class 如下

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);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core 3.1,从当前HttpContext中的referrer url获取controller和动作名称 - ASP.NET Core 3.1, get the controller and action name from referrer url in the current HttpContext 如何在 ASP.NET CORE 3.1 Web API 中捕获当前状态码 - How to capture current Status code in ASP.NET CORE 3.1 Web API 如何让用 ASP.Net Core 2.0 编写的自定义异常处理程序在 ASP.Net Core 3.1 中工作? - How can I get a custom exception handler written in ASP.Net Core 2.0 to work in ASP.Net Core 3.1? 在 ASP.NET Core 3.1 中按字段值获取实体 - Get entity by field value in ASP.NET Core 3.1 如何在 ASP.NET Core 3.1 中使用 protobuf-net 3 - How to use protobuf-net 3 with ASP.NET Core 3.1 如何在ViewComponent Asp.Net Core中获取当前登录用户 - How get current login user in ViewComponent Asp.Net Core asp.net core中如何获取当前用户 - How to get current user in asp.net core 如何在 asp.net 内核中获取当前用户 ID - How to get current userId in asp.net core Asp.net Core 3.1 绑定:在 GET 中使用字典作为参数的操作 - Asp.net Core 3.1 Binding: Action with a Dictionary as parameter in GET ASP.NET Core 3.1 - 如何获取客户的 IP 地址? - ASP.NET Core 3.1 - How do I get a client's IP Address?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM