在 ASP.NET Core 3.1 中使用新的 Json 序列化程序和 HttpContext.Response

Using new Json serializer with HttpContext.Response in ASP.NET Core 3.1

当我们想在 ASP.NET Core 的管道中将对象序列化为 JSON 字符串时,我们需要使用 HttpContext.Response.Body.WriteAsync,除非我遗漏了什么,因为没有Result 属性 我们可以很容易地使用它来分配一个 JsonResult 对象。

除非有更好的替代方法,否则使用上述方法究竟是如何实现序列化的?

注意: JSON 序列化器的选项应该与 ASP.NET Core 3.1 中使用的(默认)选项相同。

如果需要(在我们的例子中不是),可以通过 IServiceCollection.AddJsonOptions 中间件修改它们。

示例:

app.Use( next =>
{
    return async context =>
    {
        if (<someFunkyConditionalExample>)
        {
            // serialize a JSON object as the response's content, returned to the end-user.
            // this should use ASP.NET Core 3.1's defaults for JSON Serialization.
        }
        else
        {
            await next(context);
        }
    };
});

首先,您可以使用these extension methods将字符串直接写入您的响应,例如:

await context.Response.WriteAsync("some text");

确保您导入了正确的命名空间以允许您访问这些扩展:

using Microsoft.AspNetCore.Http;

其次,如果您想获取框架正在使用的JSON序列化器设置,您可以从DI容器中提取它们:

var jsonOptions = context.RequestServices.GetService<IOptions<JsonOptions>>();

所以这将使您的完整管道代码看起来有点像这样:

app.Use(next =>
{
    return async context =>
    {
        if (<someFunkyConditionalExample>)
        {
            // Get the options
            var jsonOptions = context.RequestServices.GetService<IOptions<JsonOptions>>();

            // Serialise using the settings provided
            var json = JsonSerializer.Serialize(
                new {Foo = "bar"}, // Switch this with your object
                jsonOptions?.Value.JsonSerializerOptions);

            // Write to the response
            await context.Response.WriteAsync(json);
        }
        else
        {
            await next(context);
        }
    };
});