在中间件中序列化对 JSON 的响应的最佳方法是什么?

本文关键字:响应 最佳 是什么 方法 JSON 中间件 序列化 | 更新日期: 2023-09-27 18:32:24

是否有一种规范的方法可以利用中间件中配置 ASP.NET JsonOutputFormatter?或者,更一般地说,是否有比在我的中间件中显式调用JsonConvert.SerializeObject更好的方法来序列化对 JSON 的响应?

目前,我有以下代码:

public static void HandleHealthRequests(this IApplicationBuilder app)
{
    app.Map(new PathString("/health"), builder =>
    {
        builder.Run(async context =>
        {
            string response = JsonConvert.SerializeObject(new { DateTime.UtcNow, Version = _version });
            context.Response.StatusCode = StatusCodes.Status200OK;
            context.Response.ContentType = "application/json";
            context.Response.ContentLength = response.Length;
            await context.Response.WriteAsync(response);
        });
    });
}

这工作正常,但直接调用JsonConvert.SerializeObject并直接操纵Response感觉不对。

我考虑过解决JsonOutputFormatter以直接利用它,但它需要一个看起来太复杂而无法设置的OutputFormatterContext。此外,我还尝试仅利用JsonOutputFormatter.SerializerSettings但发现它在应用程序启动时null,因此我的代码在进程开始时被抛出。

在中间件中序列化对 JSON 的响应的最佳方法是什么?

我有一个类似的问题,我只想对所有 json 响应使用相同的配置,无论它们在中间件、过滤器或控制器中......对于新版本的 .NET Core(至少使用 Microsoft.AspNetCore.Mvc.Formatters.Json 1.1.2),我在格式化程序中使用 WriteObject(TextWriter writer, object value) 方法,我在中间件或过滤器中使用依赖注入解析JsonOutputFormatter,并使用该 WriteObject 方法进行序列化。

var stringWriter = new StringWriter(CultureInfo.InvariantCulture);
jsonOutputFormatter.WriteObject(stringWriter, value);
var responseBody = stringWriter.ToString();