是否有规范的方法来利用 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/