【发布时间】: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