我在 asp.net 上有一个 Web 应用程序,它使用 Jquery-ajax 调用从 restful 服务获取一些数据。这个 WCF 服务工作正常,我可以在我的浏览器中使用它的 ' UriTemplate ' 调用它,接下来将显示我的数据。
但是,当我使用 ajax 调用来获取内容时,将记录Access-Control-Allow-Origin错误。考虑到我在 web.config 文件中设置了 Access-Control-Allow-Origin 和 Header 参数,但没有得到结果。
错误内容:
XMLHttpRequest cannot load http://localhost:8000/MonitorDataProviderService/MonitorData. Origin http://localhost:2265 is not allowed by Access-Control-Allow-Origin.
我的ajax 调用在 ascx 脚本块中:
function FillDataA()
{
console.log("Address is : " + address);
$.ajax({
type: "GET",
url: address,//Address is valid
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert("WIN");
},
error: function (msg) { console.log("ERROR"); }
});
setTimeout(function () { FillDataA(); }, 2000);//The method is calling continuously
}
配置文件标签:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:2265" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
</customHeaders>
</httpProtocol>
</system.webServer>
此外,将其添加到Global.asax并没有帮助:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin",
"*");
// I've Tested fixed url in place of '*' too
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
"GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
"1728000");
HttpContext.Current.Response.End();
}
}
使用的浏览器: - Chrome 28 - Firefox 22.0
任何有用的想法将不胜感激
此致