我可以知道当我尝试使用jQuery Ajax调用WebAPI时,下面的代码返回NetworkError的原因吗?已成功调用Web方法,但在返回后返回错误。
如果我更改了对HttpGet的访问权限,则可以使用IE访问Web方法。
所以一定是jQuery Ajax出了问题。希望有人能帮上忙。
$.ajax({
type: "POST",
async: false,
url: "http://localhost:5000/API/Test",
xhrFields: { withCredentials: true },
data: JSON.stringify(Params),
contentType: "application/x-www-form-urlencoded",
success: function (msg) {
},
error: function (XHR, errStatus, errorThrown) {
});
[Route("API/Test"), HttpPost]
public string Test()
{
JsonConvert.SerializeObject(new { Test = "Test Message" });
}发布于 2017-08-29 22:29:29
要使此功能正常工作,需要进行一些更改
1.内容类型
您使用的内容类型为"application/x-www-form-urlencoded“,但以JSON字符串的形式发送数据。将内容类型更改为"application/json“。默认情况下,Api将从json反序列化请求正文,因此它应该可以工作。
2. Api签名中无输入
Test()不会从请求体中读取任何内容。添加一个对象作为参数,匹配客户端发送的对象。
3.不返回
Api方法不返回字符串作为签名承诺。
最终结果
$.ajax({
type: "POST",
async: false,
url: "http://localhost:5000/API/Test",
xhrFields: { withCredentials: true },
data: JSON.stringify(Params),
contentType: "application/json",
success: function (msg) {
console.log(msg);
},
error: function (XHR, errStatus, errorThrown) {
console.log(errStatus);
});
[Route("API/Test"), HttpPost]
public string Test(RequestBodyDTO body)
{
return JsonConvert.SerializeObject(new { Test = "Test Message" });
}发布于 2017-08-30 07:08:21
我已经找到了我自己问题的答案。
即使我在同一台PC上调用(但使用的是jQuery Ajax),我也需要添加:
[AllowAnonymous] // To the controller和
appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // To the HttpConfiguration before any routeshttps://stackoverflow.com/questions/45938318
复制相似问题