[英]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.