【发布时间】:2012-10-16 01:29:43
【问题描述】:
在我自己的机器上调用网络服务时,我在 Chrome 中遇到错误。错误是:
Origin http://localhost:52386 is not allowed by Access-Control-Allow-Origin.
我已经阅读了其他问题here 和这样的文章:Cross Domain AJAX;但他们倾向于处理 IE 无法正常工作的问题,而我的 Chrome 也有问题。
我将以下内容添加到我的 webservice/Global.asax.cs:
protected void Application_BeginRequest(object sender, EventArgs e)
{
//HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
// Changed to this:
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:52386");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:80");
}
这是我的 HTML 代码(我需要将它保存为纯 HTML,后面没有代码):
$(document).ready(function () {
var user = 'testuser';
var pwd = 'abc123';
var auth = 'Basic ' + Base64.encode(user + ':' + pwd);
if ($.browser.msie) {
jQuery.support.cors = true;
$.ajax({
type: "GET",
url: "http://localhost/Website.Webservice/api/TaxDocument",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "text json",
headers: { Authorization: auth },
crossDomain: true,
success: function (data, textStatus, jqXHR) { ProcessOutput(data); },
error: function (jqXHR, textStatus, errorThrown) { alert('Error: ' + textStatus + ' ' + errorThrown); }
});
} else {
$.ajax({
type: "GET",
url: "http://localhost/Website.Webservice/api/TaxDocument",
data: "{}",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
headers: { Authorization: auth },
success: function (data, textStatus, jqXHR) { ProcessOutput(data); },
error: function (jqXHR, textStatus, errorThrown) { alert('Error: ' + textStatus + ' ' + errorThrown); }
});
}
})
【问题讨论】:
-
您应该在 Access-Control-Allow-Origin 标头中指定端口(如果它与源不同)。看问题:stackoverflow.com/questions/8576252/…和stackoverflow.com/questions/7113877/…星号
*在这种情况下不起作用。 -
我添加了端口 52386 和端口 80,但它仍然无法在 chrome 或 firefox 中使用。我让它在ie和safari中工作。还有其他想法吗?
-
不应该是
http://localhost:52386/- 带有斜杠吗? -
好的,我添加了斜杠,但没有帮助。我也确认这是问题所在。我将 html 页面发布到 localhost 并运行它,它可以工作。所以至少我知道我真的在处理访问控制问题。我会继续努力,找到后我会发布解决方案。
-
你的意思是,一个普通的 html 页面可以正常工作,而 ASP.NET 页面会产生错误?如果是这样,您能否记录浏览器接收到的实际 http-headers?
标签: ajax json google-chrome cors asp.net-web-api