【问题标题】:JQuery $.get returns 404 undefined from Self hosting Web APIJQuery $.get 从自托管 Web API 返回 404 undefined
【发布时间】:2013-06-18 13:33:28
【问题描述】:

我刚刚开始研究 web-api,并且已经建立了一个小型的自托管项目。我设置了一个基本控制器,当我尝试在浏览器中指向它时它会返回结果。

现在当我尝试使用 jquery.get 调用它时

例如

$.get("http://<my ip>:8082/api/stats/single/1/i")                 
    .done(function(result) {
        alert("results");
     })
    .error(function(result) { 
       alert(result.status + " " + result.responseText); }
 );};

我收到一个错误(404 未定义)

如果我在小提琴中查看上面的结果,我确实看到了我期望的 json 结果,原始标题如下......

 HTTP/1.1 200 OK
 Content-Length: 415
 Content-Type: application/json; charset=utf-8
 Server: Microsoft-HTTPAPI/2.0
 Date: Tue, 18 Jun 2013 13:04:03 GMT

如果我在另一个我知道提供测试数据的远程服务器上尝试 jquery,.get 会正确返回。我确实注意到此服务器的原始标头中有更多内容...

  HTTP/1.1 200 OK
  Cache-Control: no-cache 
  Pragma: no-cache
  Content-Length: 431
  Content-Type: application/json; charset=utf-8
  Content-Encoding: gzip
  Expires: -1
  Vary: Accept-Encoding
  Server: Microsoft-IIS/8.0
  Set-Cookie:   ARRAffinity=462716b27beb795c09df205e893d3e263b1ec9b710c92f7c4203f4b63ac1aed2;Path=/;Domain=sampleservices.devexpress.com
   Set-Cookie: ASP.NET_SessionId=j4sdehjie1h0cv2rukxnudw3; path=/; HttpOnly
   Access-Control-Allow-Origin: null
   Access-Control-Allow-Credentials: true
   X-AspNet-Version: 4.0.30319
   X-Powered-By: ASP.NET
   X-Powered-By: ARR/2.5
   X-Powered-By: ASP.NET
   Set-Cookie: WAWebSiteSID=14a8502027ea4cc3a9e65036ed421c5e; Path=/; HttpOnly
   Date: Tue, 18 Jun 2013 13:26:52 GMT

有人知道为什么我的 web-api 测试无法处理使用 $.get 的调用吗??

(对问题的回答)..

当我在 chrome 中使用我的查询时,我得到了

HTTP/1.1 200 正常 内容长度:405 内容类型:应用程序/xml;字符集=utf-8 服务器:Microsoft-HTTPAPI/2.0 日期:格林威治标准时间 2013 年 6 月 19 日星期三 05:34:33

ArrayOfStateController.State xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebApiEquipmentStatus"><StateController.State><Description>state1 description</Description><Name>state1</Name></StateController.State><StateController.State><Description>state2 description</Description><Name>state2</Name></StateController.State></ArrayOfStateController.State>

当我运行 jquery 时,我在 fiddler 中看到以下内容

HTTP/1.1 200 OK
Content-Length: 107
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Wed, 19 Jun 2013 05:35:58 GMT

[{"Name":"state1","Description":"state1 description"},{"Name":"state2","Description":"state2 description"}]

[编辑]

根据我尝试过的建议..

 enter code here


enter code here
$.ajax.crossDomain = true;          
                    getSingle = function () {
                        $.getJSON("http://<ip>/api/state/single/1/i?callback=process", 
                            {header: 'Access-Control-Allow-Origin: *'})
                            .done(function (result) {
                                var process = function(data) {
                                    $("#results").text(data.toString());
                                };

                            })
                            .error(function (result) {
                                $("#results").text(result.status + " " + result.responseText);
                            });
                    };

如果我查看 Chrome 控制台窗口,我仍然可以看到

"XMLHttpRequest cannot load http://<ip>:8082/api/state/single/1/i?callback=process. Origin null is not allowed by Access-Control-Allow-Origin. "

我花了一整天的时间在谷歌上搜索这个主题,但似乎没有任何内容指出如何解决这个问题(在介绍级别)

【问题讨论】:

  • 你看到了什么你去http://&lt;my ip&gt;:8082/api/stats/single/1/i
  • 将答案作为编辑放入原始问题中
  • 如果您在AJAX 调用中使用&lt;my ip&gt; 并将浏览器指向localhost,您可能会在调用时遇到same origin policy 挑战
  • 其实我试过了,我的ip,localhost,还有我的机器名。当我使用 .get 时,它们都不起作用,当我在浏览器中“调用”服务时,它们都起作用。此外,通过 .get 调用,服务被调用,*例如命中断点),并且在小提琴中可以看到返回的 coeect json。只是 $.get 报告一个错误。我在这里迷路了,不知道如何调试或继续解决这个问题

标签: jquery asp.net asp.net-web-api


【解决方案1】:

就像 Bart 所说,您“可能会在调用时遇到相同的源策略挑战”,这可能是因为您在 ajax 查询中使用了端口 8082,而不是在源 URL 中。你可以:

  • 不要使用那个端口
  • 使用jsonp
  • 在原始页面中使用标头“Access-Control-Allow-Origin:”和“http://&lt;my ip&gt;:8082”,并将 $.ajax()“crossDomain”选项设置为 true。

【讨论】:

  • 感谢您的反馈。我试过 $.ajax.crossDomain = true; getSingle = function () { $.getJSON("localhost/api/state/single/1/i?callback=process", {header: 'Access-Control-Allow-Origin: *'}) .done(function (result) { var process = function(data) { $( "#results").text(data.toString()); };
  • 我已将上述内容作为问题中的编辑(堆栈溢出的新手,将 localhost 替换为 因为我看不到如何在代码块中环绕
  • 我没有,但我刚刚做了,还是一样
  • 抱歉,不是在 ajax 调用中必须放置 Access-Control-Allow-Origin,而是在进行 ajax 调用的页面的 http 标头中。我不知道如何用 asp 做到这一点,但它应该是微不足道的。
  • 是的,这很可笑,到处都对此进行了如此详细的讨论,并且在标头等中有很多 Access-Control-Allow-Origin 的引用(但从未在确切的上下文中在哪里使用它)关于它的全部内容的各种文章,但没有关于在哪里使用它的真实示例!在我的例子中,它是最基本的东西,一个简单的开箱即用服务和一个简单的 jquery get,都在同一台机器上!没有别的,它就是行不通。
【解决方案2】:

嗨,终于搞定了。

作为 web-api 的新手,我只想知道如何设置此标头信息,而我需要做的不仅仅是返回结果,而是将其包装在 HttpResponseMessage 中并返回,例如

const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";

public HttpResponseMessage GetAllProducts()
        {          
          var results = GetProducts();
          HttpResponseMessage  response = Request.CreateResponse(HttpStatusCode.OK, results);
          response.Headers.Add(AccessControlAllowOrigin, "*");
          return response;
        }

无论如何感谢其他人的贡献。

【讨论】:

    猜你喜欢
    • 2015-06-12
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 2018-08-20
    相关资源
    最近更新 更多