WebAPI 爲什麼你的[FromBody]參數總是爲NULL

出於某種原因,我總是忘記Web API參數綁定的工作原理。無數次,我的[FromBody]參數爲NULL。

有時間整理一下並寫下來,防止以後再犯同樣的錯誤。

大家可以閱讀關於Web API中參數綁定的官方文檔 parameter-binding-in-aspnet-web-api

言歸正傳,這是我最初的請求,測試時不起作用:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "api/discount/saveEmailForDiscount",
    data: {email: "[email protected]"}
});

C#代碼如下:

[HttpPost, Route("api/discount/saveEmail")]
public IHttpActionResult SaveEmailForDiscount([FromBody] string email)  
{
    //do something with e-mail
    return Ok(email);
}

要強制Web API從請求主體讀取“簡單”類型,您需要將[FromBody]屬性添加到參數中。

 

Web API reads the response body at most once, so only one parameter of an action can come from the request body. If you need to get multiple values from the request body, define a complex type.

Web API最多隻讀取一次響應主體,因此只有一個操作參數可以來自請求主體。如果您需要從請求主體獲取多個值,請定義一個複雜類型。

但email的值仍然是NULL。

JavaScript代碼是我們使用的通用方法的一部分,所以這就是內容類型設置爲application/json; charset=utf-8。雖然上面提到的文章中的例子也使用了內容類型application/json,但這是我們問題的根源。

AJAX請求的默認內容類型是application/x-www-form-urlencoded; charset=UTF-8。所以,如果我們不設定內容類型,或指定它爲pplication/x-www-form-urlencoded; charset=UTF-8,它應該是正確的?

呃...不,顯然這個值應該像這樣格式化:

=value

知道這會產生最終的JavaScript代碼:

$.ajax({
   type: "POST",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", //this could be left out as it is the default content-type of an AJAX request
    url: "api/discount/saveEmailForDiscount",
    data: =+"[email protected]"
});

最後要提到的是Asp.Net網站上的評論:

Before sending a simple type, consider wrapping the value in a complex type instead. This gives you the benefits of model validation on the server side, and makes it easier to extend your model if needed.

在發送簡單類型之前,請考慮將值包裝在複雜類型中。這爲您提供了服務器端模型驗證的好處,並且可以在需要時擴展模型

轉載於:https://www.cnblogs.com/dxxzst/p/8777616.html 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章