asp.net-mvc - ASP.NET WebAPI 帖子正文中的空值?

标签 asp.net-mvc json asp.net-web-api

今天刚开始学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/

相关文章:

asp.net-mvc - 使用 cookie 与第三方登录提供商和 Microsoft.AspNet.Identity.Owin 2.0 保持登录状态

Java 对象转 JSON : Ignore Cycle

javascript - 在某些浏览器中日期返回为 "Undefined"和 "NaN"?

sql - 在 postgresql 中编辑 jsonb 数组的字段

asp.net-mvc - Asp.net mvc通过httpClient连接webApi

asp.net - Web Api 帮助页面来自 1 个以上文件的 XML 注释

c# - 使用数组将多个参数从 View 传递到 Controller

c# - 你如何在 Entity Framework 中编写参数化的 where-in 原始 sql 查询

asp.net-mvc - 在 MVC 3 中删除 Azure Blob

angular - 如何使用 msbuild 从 dotnetcore web-api 项目中触发 "ng build",但将 Angular 项目保存在单独的文件夹中?