[英]ASP.NET WebAPI Null value in post body?
我今天剛剛開始學習WebAPI,我無法弄清楚為什么“帳戶”始終為空。
請求
Content-Type: application/json; charset=utf-8
Request-Body: {"account":{"email":"awd","password":"awad","isNewsletterSubscribed":false}}
的WebAPI
public class AccountsController : ApiController
{
public void Post([FromBody] string account)
{
// account is null
}
}
在這種情況下,帳戶不應該包含json字符串嗎?
在這種情況下,帳戶不應該包含json字符串嗎?
這取決於您發送請求時設置的特定Content-Type
請求標頭。 例如,如果您使用默認的application/x-www-form-urlencoded
,則您的請求正文有效負載必須如下所示:
={"account":{"email":"awd","password":"awad","isNewsletterSubscribed":false}}
注意開頭的=
字符。 這是我遇到過的最奇怪的事情之一。 因為如果請求Web API不期望參數名稱,而只是綁定值,則只能從主體綁定一個參數。
話雖如此,您的請求有效負載看起來更像是JSON。 因此,設計視圖模型並在發送請求時使用Content-Type: application/json
會更有意義。 將JSON對象綁定到字符串不常見。
所以:
public class UserViewModel
{
public string Email { get; set; }
public string Password { get; set; }
public bool IsNewsletterSubscribed { get; set; }
}
public class AccountViewModel
{
public UserViewModel Account { get; set; }
}
然后您的控制器操作將簡單地將視圖模型作為參數。 在這種情況下,您不需要使用[FromBody]
屬性來裝飾它,因為按照Web API中的約定,默認模型綁定器將嘗試從請求主體綁定復雜類型:
public class AccountsController : ApiController
{
public HttpResponseMessage Post(AccountViewModel model)
{
// work with the model here and return some response
return Request.CreateResponse(HttpStatusCode.OK);
}
}
另請注意,由於HTTP是一個請求/響應協議,因此讓Web API控制器操作返回響應消息更有意義,如我的示例所示,而不僅僅是使用一些void
方法。 這使代碼更具可讀性。 您可以立即了解服務器將如何響應以及指定請求的狀態代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.