我今天刚刚开始学习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
方法.这使代码更具可读性.您可以立即了解服务器将如何响应以及指定请求的状态代码.