Reputation: 5442
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.
Upvotes: 9
Views: 7169
Reputation: 311
You can write a middleware class that inherits from ActionResult as follows
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);
}
Upvotes: 1
Reputation: 10035
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);
}
Upvotes: 14