【问题标题】:OWIN WebAPI 2 jQuery Ajax getting NetworkErrorOWIN WebAPI 2 jQuery Ajax 获取 NetworkError
【发布时间】:2017-08-29 11:46:34
【问题描述】:

当我尝试使用 jQuery Ajax 调用 WebAPI 时,我可以知道为什么下面的代码返回 NetworkError 的原因吗? 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" });
}

【问题讨论】:

  • 失败时errStatuserrorThrown 变量的值是多少?
  • 1) 如果您将一些数据发布到该方法,该方法应该在 [FromBody] 参数中接收它。 2)该方法不返回任何东西。 3) 如果你传递 JSON 数据给它,内容类型应该是 application/json

标签: jquery ajax owin webapi2


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回答。但是它不起作用。 1. 如果我更改为“application/json”,则根本不会调用 WebApi。 2. 在这种情况下输入Params 不是必须的,不影响调用,WebAPI 会很乐意忽略它。 3.它确实返回一个Json字符串
  • 好的,那么在Startup.cs的media type formatter配置中检查json的内容类型是否添加,如果不需要参数为什么要通过ajax调用发送?
【解决方案2】:

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

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

[AllowAnonymous] // To the controller

appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // To the HttpConfiguration before any routes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多