0

NetworkError当我尝试使用 jQuery Ajax 调用 WebAPI 时,我可以知道以下代码返回的原因吗?Web方法调用成功,返回后报错。

如果我更改对 HttpGet 的访问权限,我可以使用 IE 访问 Web Method。

所以 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" });
}
4

2 回答 2

0

需要进行一些更改才能使这项工作

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-29T14:29:29.077 回答
0

我已经找到了我自己的问题的答案。

即使我从同一台 PC 调用(但使用 jQuery Ajax),我也需要添加:

[AllowAnonymous] // To the controller

appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // To the HttpConfiguration before any routes
于 2017-08-29T23:08:21.043 回答