I use System.Text.Json and I set JsonSerializerOptions in ConfigureServices method of Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
...
}
Now I want get current JsonSerializerOptions in CustomErrorHandlingMiddleware
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.
public async Task Invoke(HttpContext httpContext, IOptions<JsonOptions> options)
{
JsonSerializerOptions serializerOptions = options.Value.JsonSerializerOptions;
await _next(httpContext);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With