Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

 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.

like image 920
Ramil Aliyev Avatar asked Mar 03 '23 13:03

Ramil Aliyev


1 Answers

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);
}
like image 166
weichch Avatar answered Mar 06 '23 01:03

weichch