The*_*hea 4 ajax http-post asp.net-web-api angularjs
我已经创建了一个ASP.Net API控制器,我正在尝试使用Angular发出POST请求.请求到达我的控制器方法,但参数值为null.
我的角色代码:
$http({ method: 'POST', url: '/api/Contents', data: "value=foobar", headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).
success(function(data) {
}).
error(function(data, status, headers, config) {
});
Run Code Online (Sandbox Code Playgroud)
我也试过json(Json是我最想要的):
$http({ method: 'POST', url: '/api/Contents', data: { "foo": "bar", "foo2": "bar2" }, headers: { 'Content-Type': 'application/json'} }).
success(function(data) {
}).
error(function(data, status, headers, config) {
});
Run Code Online (Sandbox Code Playgroud)
我的(非常简单)Controller方法如下所示:
public void Post([FromBody]string value)
{
//But Value is NULL!!!!!!
}
Run Code Online (Sandbox Code Playgroud)
以下是我从Chrome中删除的请求标题中的一些值(我认为可能很有趣:
我错过了什么?
像这样:
$http({
method: 'POST',
url: '/api/Contents',
data: "=foobar",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(data) {
}).error(function(data, status, headers, config) {
});
Run Code Online (Sandbox Code Playgroud)
注意=foobar数据参数.在这种情况下,您不应指定参数名称.是的,我知道,不要问.
你可以阅读更多相关信息how model binding in the Web API works.如果你像我一样发现这绝对是疯了,你可以考虑ServiceStack改用.
或者,您可以使用视图模型:
public class ContentsModel
{
public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后让控制器操作将视图模型作为参数:
public void Post(ContentsModel model)
{
}
Run Code Online (Sandbox Code Playgroud)
现在您可以发送正常的JSON请求:
$http({
method: 'POST',
url: '/api/Contents',
data: JSON.stringify({ "value": "the value" }),
headers: { 'Content-Type': 'application/json' }
}).success(function(data) {
}).error(function(data, status, headers, config) {
});
Run Code Online (Sandbox Code Playgroud)
另请注意,如果要发送JSON,则需要使用该JSON.stringify方法将javascript对象转换为JSON字符串.
| 归档时间: |
|
| 查看次数: |
3357 次 |
| 最近记录: |