今天刚开始学WebAPI,想不通为什么“account”总是null。
请求
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 字符串吗?
最佳答案
Shouldn't account contain a json string in this case?
这取决于您在发送请求时设置的特定 Content-Type
请求 header 。例如,如果您使用默认的 application/x-www-form-urlencoded
,那么您的请求正文负载必须如下所示:
={"account":{"email":"awd","password":"awad","isNewsletterSubscribed":false}}
注意开头的 =
字符。这是我遇到过的最奇怪的事情之一。如果请求 Web API 不需要参数名称,而只需要值,那么您只能从正文中绑定(bind)一个参数。
话虽这么说,您的请求负载看起来更像是一个 JSON。因此,设计一个 View 模型并在发送请求时使用 Content-Type: application/json
会更有意义。将 JSON 对象绑定(bind)到字符串并不常见。
所以:
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; }
}
然后您的 Controller 操作将简单地将 View 模型作为参数。在这种情况下,您不需要使用 [FromBody]
属性对其进行修饰,因为按照 Web API 中的约定,默认模型绑定(bind)器将尝试绑定(bind)请求正文中的复杂类型:
public class AccountsController : ApiController
{
public HttpResponseMessage Post(AccountViewModel model)
{
// work with the model here and return some response
return Request.CreateResponse(HttpStatusCode.OK);
}
}
另请注意,由于 HTTP 是一种请求/响应协议(protocol),因此让您的 Web API Controller 操作返回响应消息(如我的示例所示)比仅使用一些 void
方法更有意义。这使代码更具可读性。您立即了解服务器将如何响应以及对指定请求的状态代码。
关于asp.net-mvc - ASP.NET WebAPI 帖子正文中的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20804080/