【问题标题】:web api 2 post with parameter - must use json.stringyfi带有参数的 web api 2 帖子 - 必须使用 json.stringify
【发布时间】:2016-04-05 11:18:44
【问题描述】:

我正在使用 angularjs,我正在尝试对我的 web api 进行 HttpPost 调用。

我的api方法:

[HttpPost]
    [Route("authentication/getkey")]
    public IHttpActionResult GetKey([FromBody]string password) {
        //Do stuff
    }

我的电话:

service.getKey = function (password) {
            return $http.post('api/authentication/getkey', JSON.stringify(password))
                .then(function(result) {
                    return result.data;
                });
        }

现在这工作正常,但我真的需要使用JSON.stringify 吗?我尝试像下面这样发送它,但所有这些都得到密码 = null。我必须使用JSON.stringify 还是我在其他示例中做错了?

//Doesnt work
service.getKey = function (password) {
    return $http.post('api/authentication/getkey', password)
        .then(function(result) {
             return result.data;
         });
    }

//Doesnt work
service.getKey = function (password) {
    return $http.post('api/authentication/getkey', {password})
        .then(function(result) {
             return result.data;
         });
    }

【问题讨论】:

  • 您需要将 POST 请求中的数据以 JSON 格式发送,因为默认情况下,角度 $http 服务将 Content-Type 发送为 application/json。 JSON.stringify 会将您的数据转换为 JavaScript 对象表示法 (JSON) 字符串。您是否有不想使用 JSON.stringify 的原因?一种方法是更改​​ Content-Type。如果你愿意,我可以提供一些示例代码。
  • @VivekN 请这样做。我只是想看看如何做的其他例子——或者我应该怎么做

标签: angularjs json asp.net-web-api http-post asp.net-web-api2


【解决方案1】:

如果您不想使用 JSON.stringify,另一种选择是将数据作为 application/x-www-form-urlencoded 发送,正如其他答案中所指出的那样。这样您就可以将数据作为表单数据发送。我不确定 $http.post Shortcut 方法的语法,但想法是一样的。

service.getKey = function (password) {
    $http({
            method: 'POST',
            url: 'api/authentication/getkey',
            data: $.param({ '': password }),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
 .then(function(result) {
             return result.data;
         });

【讨论】:

    【解决方案2】:

    来自微软关于Parameter Binding in ASP.NET Web API的Web API官方文档:

    当参数有 [FromBody] 时,Web API 使用 Content-Type 标头来选择格式化程序。在此示例中,内容类型为“application/json”,请求正文为原始 JSON 字符串(不是 JSON 对象)。

    Angular $http 服务在 POST 请求中默认发送 Content-Type: application/json 作为标头,正如您从 official docs 中看到的那样,因此 Web API 正在尝试使用他的 JsonFormatter 绑定您的请求正文。因此,您必须为他提供格式良好的 Json 字符串(不是内部带有字符串的 Json 对象)才能正确绑定他的原始字符串参数。

    附带说明一下,您也可以使用 application/x-www-form-urlencoded 作为 Content-Type 标头发送请求,但是您必须将正文格式化为表单参数(使用类似于 jQuery $.param( .. ) 的东西)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      • 2015-06-17
      • 2019-12-04
      • 1970-01-01
      • 2013-10-17
      相关资源
      最近更新 更多