ASP.NET Core 3.1 如何让控制器使用 System.Text.Json 序列化和反序列化

ASP.NET Core 3.1 How can I get the controller to use System.Text.Json to serialize and deserialize

我正在从 .NET CORE 2.2 转换到 3.1。是否可以强制控制器使用 System.Text.Json 序列化和反序列化任何传入的请求和响应?基本上,当收到请求时我想使用 System.Text.Json,当响应发出时我想使用 System.Text.Json。如果是,如何?

这样做的原因是微软确实在推动这个库作为 Newtonsoft.Json 的替代品,因为它更加安全和快速。但是,我似乎无法在 Microsoft 的页面上找到任何反映这一点的文档。我发现微软很难不更新他们的代码来使用这个新库。

更新

我无法通过 application/vnd.api+json 解析来让 System.Text.Json 绑定模型 - 模型为 NULL。它只会在我使用 application/json 解析时绑定。这是有问题的,因为 JSON:API 规范要求 application/vnd.api+json(参见此处:)。我尝试用 [Consumes("application/vnd.api+json")] 装饰控制器,但这不起作用。

如何让 System.Text.Json 使用 application/vnd.api+json 绑定模型?我问这个问题的最初假设是 .NET Core 3.1 没有使用 System.Text.Json。由于没有人提供答案,除了一些评论,我选择扩展这个问题。

更改密码模型:

using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;

namespace ABC.Model.Clients
{
    public class ChangePassword
    {   
        public ChangePassword() { }

        [Required]
        [JsonPropertyName("old-password")]
        public string OldPassword { get; set; }

        [Required]
        [JsonPropertyName("new-password")]
        public string NewPassword { get; set; }

        [Required]
        [JsonPropertyName("confirm-password")]
        public string ConfirmPassword { get; set; }
    }
}

邮递员请求:

{ 
    "data": {
        "attributes": {
            "old-password" : "**********",
            "new-password" : "**********",
            "confirm-password" : "**********"
        },
        "type": "change-passwords"
    }
}

.NET Core 3.0 默认使用 System.Text.Json。还要检查描述此内容的 official documentation article

关于 .NET Core 3.0 中的 application/vnd.api+jsonJSON:API 支持。我不知道 ASP.NET Core 对此有任何支持。这是一个独立于纯网络 API 的标准。您不能只是将其添加为您接受的另一种类型并期望它起作用。

我在 GitHub JSON API .Net Core 上找到了一个项目,它提供了构建 JSON:API 兼容的框架网络 API 服务。 .NET Core 3.0 的版本目前仍处于 Alpha 阶段,目前使用的 Newtonsoft.Json 不是您想要的。您可以查看源代码以了解如何处理此类请求,并可能基于它构建您自己的解决方案。或者加入该项目并帮助他们也制作一个 System.Text.Json 版本。

您需要为 SystemTextJsonInputFormatterSupportedMediaTypes 添加 application/vnd.api+json 媒体类型。

services.AddMvc(options =>
{
    var formatter = options.InputFormatters.OfType<SystemTextJsonInputFormatter>().FirstOrDefault();
    formatter.SupportedMediaTypes.Add("application/vnd.api+json");
});