AJAX 请求:
$.ajax({
url: url,
dataType: 'json',
type: 'Post',
data: {token:"4", feed:{"id":0,"message":"Hello World","userId":4} }
});
服务器端 Web API:
[HttpPost]
public HttpResponseMessage Post(string token, Feed feed)
{
/* Some code */
return new HttpResponseMessage(HttpStatusCode.Created);
}
错误代码 404: {"message":"未找到匹配的 HTTP 资源
请求 URI 'localhost:8080/api/feed'。","messageDetail":"无操作
在与请求匹配的控制器“Feed”上找到了。”}
为什么我会收到此错误以及为什么我无法将多个参数发布到我的 API?
首先编写视图模型:
public class MyViewModel
{
public string Token { get; set; }
public Feed Feed { get; set; }
}
您的控制器操作将作为参数:
[HttpPost]
public HttpResponseMessage Post(MyViewModel model)
{
/* Some code */
return new HttpResponseMessage(HttpStatusCode.Created);
}
最后调整您的 jQuery 调用以将其作为 JSON 发送:
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
token: '4',
feed: {
id: 0,
message: 'Hello World',
userId: 4
}
})
});
AJAX 调用需要注意的重要事项:
- 设置请求
contentType
to application/json
- 将数据包装在
JSON.stringify
函数有效地将 javascript 对象转换为 JSON 字符串
- 删除了无用的
dataType: 'json'
范围。 jQuery 会自动使用Content-Type
服务器发送的响应头来推断如何解析传递给服务器的结果success
打回来。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)