我正在尝试从一个“远程”网站获取一些json数据。我在99000端口上运行web服务,然后在99001端口(http://localhost:99001/index.html)上启动我的网站。
我得到以下消息:
XMLHttpRequest cannot load http://localhost:99000/Services.svc/ReturnPersons. Origin http://localhost:99001 is not allowed by Access-Control-Allow-Origin.
即使我以HTML文件的形式启动我的网页,我也会得到这样的结果:
XMLHttpRequest cannot load http://localhost:99000/Services.svc/ReturnPersons.Origin null is not allowed by Access-Control-Allow-Origin.
web服务返回数据。我尝试像这样捕获数据项:
var url = "http://localhost:99000/Services.svc/ReturnPersons";
$.getJSON(url, function (data) {
success: readData(data)
});
function readData(data) {
alert(data[0].FirstName);
}
我试图得到这样的结构:
[{"FirstName":"Foo","LastName":"Bar"},{"Hello":"Foo","LastName":"World"}]
你知道为什么我会收到这个错误吗?
发布于 2011-02-10 10:57:21
在新的jQuery 1.5中,您可以使用:
$.ajax({
type: "GET",
url: "http://localhost:99000/Services.svc/ReturnPersons",
dataType: "jsonp",
success: readData(data),
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
})
发布于 2014-02-04 05:02:21
找到了一种可能的解决方法,但我不相信上面提到了。
下面是对这个问题的一个很好的描述:http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
基本上,只要您使用表单/url编码/纯文本内容类型,就可以了。
$.ajax({
type: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'text/plain'
},
dataType: "json",
url: "http://localhost/endpoint",
data: JSON.stringify({'DataToPost': 123}),
success: function (data) {
alert(JSON.stringify(data));
}
});
我在ASP.NET WebAPI2中使用它。所以在另一端:
public static void RegisterWebApi(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}
这样,在解析纯文本内容类型时就可以使用Json格式化程序。
别忘了在Web.config中:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol>
希望这能有所帮助。
发布于 2016-11-24 01:27:27
我使用的是WebAPI 3,也面临着同样的问题。随着@Rytis添加了他的解决方案,这个问题已经解决了。我认为在WebAPI 3中,我们不需要定义方法RegisterWebApi
。
我的更改只在web.config文件中,并且正在生效。
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol>
感谢你的解决方案@Rytis!
https://stackoverflow.com/questions/3828982
复制相似问题