簡體   English   中英

asp.net 核心 3 webapi:名稱中帶有連字符的路由或綁定參數(查詢或發布)

[英]asp.net core 3 webapi : Route or Bind parameters (query or posted) with hyphens in their name

我希望像這樣的動作簽名

[HttpPost]
public string Post(string thirdPartySpecifiedParameter)

會自動綁定帶連字符的查詢參數

controller?third-party-specified-parameter=value

或 JSON 發布值

{ "third-party-specified-parameter":"value" }

並將其分配給thirdPartySpecifiedParameter但它沒有。 路由文檔處理在 Urls 路徑中映射連字符的示例,但不處理對 C# 無效的綁定參數和字段名稱。

將傳入的帶連字符的名稱綁定到匹配的 C# 參數的最簡單方法是什么?

首先,問題是關於綁定而不是路由,最簡單的可用解決方案是使用.Net 提供的BindingAttribute 限制 - 不是新的 - 是您需要不同的 BindingAttribute 查詢參數與 Json Body vs Form post。

[HttpPost]
public string Post(
    [FromBody]PostModel model,
    [FromQuery(Name="kebab-case-query-param")]string kebabCaseQueryParam)

[FromQuery(Name="...")]處理查詢字符串參數

對於 Json 的帖子,你必須在方法簽名中使用[FromBody]屬性,定義一個 model,在該屬性上放置一個Attribute以進行綁定。 Newtonsoft.Json或 new-in-core-3 System.Text.Json使用略有不同的Attribute名稱:

public class PostModel
{
    //This one if you are using Newtonsoft.Json
    [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() ,而對於新的System.Text.Json ,您不需要。 是這樣的:

    public void ConfigureServices(IServiceCollection services)
    {
        //if using NewtonSoft
        services.AddMvc().AddNewtonsoftJson();
    
        //if using System.Text.Json
        //dotnet new webapi for netcore3 generates this code:
        services.AddControllers();
        
    }

要在 NetCore3 下以這種方式使用 Newtonsoft Json,你依賴於 nuget package Microsoft.AspNetCore.Mvc.NewtonsoftJson

暫無
暫無

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

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