Как получить текущие JsonSerializerOptions в ASP. NET Core 3.1? - PullRequest
0 голосов
/ 18 апреля 2020

Я использую System.Text. Json и я устанавливаю JsonSerializerOptions в методе ConfigureServices для Startup.cs

 public void ConfigureServices(IServiceCollection services)
 { 
 ...
            services.AddControllers()
                    .AddJsonOptions(options =>
                    {
                        options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                    });
 ...
 }

Теперь я хочу получить текущие JsonSerializerOptions в 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);
            }
        }

Как могу ли я достичь этого? Спасибо.

1 Ответ

1 голос
/ 18 апреля 2020

Вы можете добавить IOptions<JsonOptions> или IOptionsSnapshot<JsonOptions> согласно Шаблон параметров в ваше промежуточное ПО.

public async Task Invoke(HttpContext httpContext, IOptions<JsonOptions> options)
{
    JsonSerializerOptions serializerOptions = options.Value.JsonSerializerOptions;

    await _next(httpContext);
}
...