【发布时间】: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