簡體   English   中英

.Net core 3.0 API 不使用連字符綁定屬性

[英].Net core 3.0 API doesn't bind properties with hyphen

回顧了這個問題,因為上次沒有收到很好的答復。 希望我在下面提供了所有必需的信息。

我有一個基本的 API 控制器,我的 Json 對象似乎沒有正確綁定到模型。 根對象綁定,但名稱中帶有連字符的屬性不綁定。 不幸的是,我不能刪除屬性名稱中的連字符。

如何讓屬性正確綁定?

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace TestCoreAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        // POST: api/Test
        [HttpPost]
        public string Post([FromBody] TestPayload testPayload)
        {
            if (testPayload == null)
            {
                return "Test payload is empty";
            }

            if (string.IsNullOrWhiteSpace(testPayload.TestProperty))
            {
                return "Test property is empty";
            }

            return "Valid input - " + testPayload.TestProperty;
        }
    }

    [JsonObject("test-payload")]
    public class TestPayload
    {
        [JsonProperty(PropertyName = "test-property")]
        public string TestProperty { get; set; }
    }
}

這是我對 API 的調用

POST /api/test HTTP/1.1
Content-Type: application/json

{"test-property":"some string value"}

Net Core 3.1 確實綁定了連字符。 無論哪種方式,這兩個選項都是Newtonsoft.Json或 new-in-core-3 System.Text.Json ,它們使用的Attribute名稱略有不同:

public class PostModel
{
    //This one if you are using Newtonsoft.Json
    //The Nuget dependency is Microsoft.AspNetCore.Mvc.NewtonsoftJson
    [JsonProperty(PropertyName = "kebab-case-json-field")]

    //This one of you are using the new System.Text.Json.Serialization
    [JsonPropertyName("kebab-case-json-field")]

    public string kebabCaseProperty { get; set; }
}

同時,在您的Startup.cs ,要使用 Newtonsoft,您需要AddMvc() ,而對於 new System.Text.Json,您不需要。 這些都對我有用:

public void ConfigureServices(IServiceCollection services)
{
    //if using NewtonSoft
    services.AddMvc().AddNewtonsoftJson();

    //if using System.Text.Json.
    //This is the code that core 3 `dotnet new webapi` generates
    services.AddControllers();
}

您是否在Startup.ConfigureServices AddNewtonsoftJson()添加到您的服務中? 如果不是,則使用的是新的System.Text.Json ,而不是 Newtonsoft。 我認為您需要執行AddNewtonSoftJson()因為我很確定System.Text.Json不支持“kebab case”綁定。

https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#newtonsoftjson-jsonnet-support

暫無
暫無

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

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