简体   繁体   English

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

[英]What is the best way to serialize the response to JSON inside middleware?

Is there a canonical way to leverage the configured JsonOutputFormatter inside ASP.NET middleware? 是否有规范的方法来利用ASP.NET中间件中配置的JsonOutputFormatter Or, more generically, is there a better way to serialize the response to JSON than explicitly calling JsonConvert.SerializeObject in my middleware? 或者,更一般地说,是否有更好的方法来序列化对JSON的响应,而不是在我的中间件中显式调用JsonConvert.SerializeObject

Currently, I have the following code: 目前,我有以下代码:

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);
        });
    });
}

This works fine, but calling JsonConvert.SerializeObject directly and manipulating the Response directly doesn't feel right. 这工作正常,但直接调用JsonConvert.SerializeObject并直接操作Response感觉不对。

I looked at resolving the JsonOutputFormatter to leverage it directly but it requires an OutputFormatterContext which looks too complicated to set up. 我查看了解析JsonOutputFormatter以直接利用它,但它需要一个看起来太复杂而无法设置的OutputFormatterContext Additionally, I also tried just leveraging JsonOutputFormatter.SerializerSettings but found it to be null on app startup so my code was throwing when the process started. 此外,我还试图利用JsonOutputFormatter.SerializerSettings但发现它在应用程序启动时为null ,因此我的代码在进程启动时抛出。

I have a similiar problem, i just want to use the same configuration for all my json responses regardless they are inside a middleware or a filter or controller... with the new versions of .net core (at least with Microsoft.AspNetCore.Mvc.Formatters.Json 1.1.2 ) i use the WriteObject(TextWriter writer, object value) method inside the formatter, i resolve the JsonOutputFormatter with dependency injection inside my middleware or filter and use that WriteObject method for serialization. 我有一个类似的问题,我只是想对我所有的json响应使用相同的配置,无论它们是在中间件或过滤器或控制器中......使用新版本的.net核心(至少使用Microsoft.AspNetCore.Mvc.Formatters.Json 1.1.2 )我在格式化程序中使用WriteObject(TextWriter writer, object value)方法,我在我的中间件或过滤器中使用依赖注入解析JsonOutputFormatter并使用该WriteObject方法进行序列化。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM