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

标签 c# asp.net-core json.net asp.net-core-mvc

是否有规范的方法来利用 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 响应使用相同的配置,无论它们在中间件、过滤器或 Controller 中......使用新版本的 .net 核心(至少使用 Microsoft.AspNetCore.Mvc.Formatters.Json 1.1.2) 我在格式化程序中使用 WriteObject(TextWriter writer, object value) 方法,我解析了 JsonOutputFormatter 在我的中间件或过滤器中使用依赖注入(inject),并使用 WriteObject 方法进行序列化。

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

关于c# - 在中间件中序列化对 JSON 的响应的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35088250/

相关文章:

c# - 无法连接到任何指定的 MySQL 主机。 <添加名称 ="MySqlSiteMapProvider"

c# - .NET Framework (4.8) 的 Cake runner 不获取环境变量

c# - 写入第三方 API

c# - 这个计算 Code128 条码校验位的代码是否正确?

c# - 发布后 Controller 中收到的模型为空

c# - ASP.NET Web-api 核心 : Handling client connections problems and find conflicts

c# - 如何解决 DbContext 中的循环依赖

asp.net-core - 如何在不打开浏览器页面的情况下运行 ASP.NET 5

c# - 使用c#从json数据中获取值

c# - 使用 JsonConverter 的 Json.NET 自定义序列化 - 如何获得 "default"行为