在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
,因此我的代码在进程启动时会抛出异常。