【问题标题】:Using new Json serializer with HttpContext.Response in ASP.NET Core 3.1在 ASP.NET Core 3.1 中使用带有 HttpContext.Response 的新 Json 序列化程序
【发布时间】:2020-06-27 15:37:35
【问题描述】:

当我们想在 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);
        }
    };
});

【问题讨论】:

  • 我相信原生 JSON 支持是通过 System.Text.Json 添加的。您是否尝试过使用它? devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis
  • 您可以这样发送对象,以便 .net 运行时本身将其序列化为 json 并将响应作为 json 发送给调用者。类似于下面的那个。 // GET api/authors/RickAndMSFT [HttpGet("{alias}")] public Author Get(string alias) { return _authors.GetByAlias(alias); }
  • 我对你的问题感到困惑。你到底想做什么?你只是想连载吗?所以像var json = System.Text.Json.JsonSerializer.Serialize(new {x = 5})?
  • 有一个扩展方法可以直接处理字符串docs.microsoft.com/en-us/dotnet/api/…

标签: c# json asp.net-core httpcontext asp.net-core-middleware


【解决方案1】:

首先,您可以使用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);
        }
    };
});

【讨论】:

  • 哇! RequestServices 就在HttpContext 中。很高兴知道这一点。
  • JsonOptions 在什么命名空间?
  • 我使用目标框架 .NET Core 3.1 创建了一个库。然后我添加了 Microsoft.AspNetCore.Mvc 包,但找不到 JsonOptions
  • 我添加了解决问题的 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包。但我不想依赖 Json.NET。我更喜欢 System.Text.Json
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 2021-07-18
  • 2021-01-27
相关资源
最近更新 更多