web api 2 post with parameter - 必须使用 json.stringyfi

web api 2 post with parameter - must use json.stringyfi

我正在使用 angularjs 并且正在尝试对我的网站 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 吗?我尝试像下面那样发送它,但所有人都得到 password = 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;
         });
    }

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

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).

Angular $http 服务在 POST 请求中默认将 Content-Type: application/json 作为 header 发送,正如您从 official docs 中看到的那样,所以 Web API 正在尝试使用他的 JsonFormatter 绑定您的请求 body。因此,您必须向他提供格式正确的 Json 字符串(而不是 Json Object 内有字符串)以正确绑定他的原始字符串参数。

作为旁注,您也可以使用 application/x-www-form-urlencoded 作为 Content-Type header 发送请求,但是您必须将 body 格式化为表单参数(使用类似于 jQuery $.param( .. ) 的内容)

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

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;
         });