我使用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);
}
}
我该如何实现这个?谢谢。