【问题标题】:What is the best way to serialize the response to JSON inside middleware?在中间件中序列化对 JSON 的响应的最佳方法是什么?
【发布时间】:2017-12-28 20:41:43
【问题描述】:

有没有一种规范的方式来利用 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,因此我的代码在进程启动时抛出。

【问题讨论】:

  • 请注意,这与地图无关。
  • 这对于一个简单的组件来说看起来不错。 JsonOutputFormatter 适用于像 MVC 这样更复杂的环境。
  • 是的,我跳上了 jabbr,@davidfowl 基本上说了这么多。谢谢
  • @DavidPeden 你有没有找到更优雅的解决方案?
  • 不。这很简单而且有效。显然,如果您想整理或在其他地方重用它,您可以将调用捆绑到一个方法或其他东西中。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-07-29
    • 2010-09-27
    • 2021-10-24
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 2015-01-29
    相关资源
    最近更新 更多