繁体   English   中英

在 ASP.NET Core 3.1 中使用带有 HttpContext.Response 的新 Json 序列化器

[英]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);
        }
    };
});

首先,您可以使用这些扩展方法将字符串直接写入您的响应中,例如:

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

暂无
暂无

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

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