簡體   English   中英

ASP.NET Core 3.1 如何讓 controller 使用 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。 是否可以強制 controller 使用System.Text.Json序列化和反序列化任何傳入的請求和響應? 基本上,當請求進來時,我想使用System.Text.Json而當響應發出時,我想使用System.Text.Json 如果是,如何?

這樣做的原因是微軟確實在推動這個庫作為Newtonsoft.Json的替代品,因為它更安全、更快。 但是,我似乎在 Microsoft 的頁面上找不到任何反映這一點的文檔。 我發現微軟不會更新他們的代碼來使用這個新庫很難。

更新

I am unable to get System.Text.Json to bind the model by parsing with application/vnd.api+json - the model is NULL. 只有當我使用application/json解析時它才會綁定。 這是有問題的,因為 JSON:API 規范需要application/vnd.api+json (參見此處: https://stackoverflow.com/a/376456 我嘗試用[Consumes("application/vnd.api+json")]裝飾 controller ,但這不起作用。

如何獲取System.Text.Json以使用application/vnd.api+json綁定模型? 我提出這個問題的最初假設是 .NET Core 3.1 沒有使用System.Text.Json 由於除了一些評論之外沒有人提供答案,我選擇擴展這個問題。

更改密碼 Model:

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

Postman 請求:

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

.NET Core 3.0 默認使用 System.Text.Json。 另請查看描述此內容的官方文檔文章

關於 .NET Core 3.0 中的application/vnd.api+jsonJSON:API支持。 我不知道 ASP.NET 核心對此有任何支持。 這是與普通 web API 不同的標准。 您不能只是將其添加為您接受的另一種類型並期望它起作用。

I found a project on GitHub JSON API.Net Core that provides a framework for building JSON:API compliant web API services. .NET Core 3.0 的版本目前仍處於 Alpha 階段,目前使用 Newtonsoft.Json,這不是您想要的。 您可以查看源代碼以了解如何處理此類請求,並可能基於它構建您自己的解決方案。 或者加入項目並幫助他們制作System.Text.Json版本。

您需要為 SystemTextJsonInputFormatter 的SupportedMediaTypes添加 application/ SystemTextJsonInputFormatter application/vnd.api+json媒體類型。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM