Ramil Aliyev 007
Ramil Aliyev 007

Reputation: 5442

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.

Upvotes: 9

Views: 7169

Answers (2)

mincasoft
mincasoft

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

weichch
weichch

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

Related Questions