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

Sup*_*Bob 6 c# json httpcontext asp.net-core asp.net-core-middleware

当我们想在 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);
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

Dav*_*idG 5

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

await context.Response.WriteAsync("some text");
Run Code Online (Sandbox Code Playgroud)

确保您已导入正确的命名空间,以便您可以访问这些扩展:

using Microsoft.AspNetCore.Http;
Run Code Online (Sandbox Code Playgroud)

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

var jsonOptions = context.RequestServices.GetService<IOptions<JsonOptions>>();
Run Code Online (Sandbox Code Playgroud)

因此,这将使您的完整管道代码看起来像这样:

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);
        }
    };
});
Run Code Online (Sandbox Code Playgroud)