【发布时间】:2020-02-22 02:45:23
【问题描述】:
我们有两个使用两个 WCF 调用的 HTML 页面。两种 WCF 方法都在同一个项目下,部署时在http://MyServer:89 下。由于web.config 有以下问题,我们对 CORS 没有任何问题:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept"/>
</customHeaders>
[OperationContract] 看起来像这样:
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "GetData")]
System.IO.Stream GetData();
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "GetMoreData")]
System.IO.Stream GetMoreData();
两个 HTML 页面也在同一服务器中,但端口不同 (http://MyServer:93)。
GetData() 由带有 AM Charts javascript 控件的 HTML 调用。调用看起来像这样,并且在过去几个月中运行良好:
"dataLoader": {
"url": "http://MyServer:89/Service1.svc/GetData",
就在今天,我为另一个 HTML 页面创建了 GetMoreData()。函数调用如下所示:
var serviceUri = "http://MyServer:89/Service1.svc/GetMoreData";
$.ajax({
type: "GET",
contentType: "application/json",
url: serviceUri,
dataType: "json",
success:
function (response) {
showPresidentsList(response);
$('#message').html("<a href=" + serviceUri + ">" + serviceUri + "</a>");
},
error:
function (err) {
alert(err);
}
});
第二个电话给了我 CORS 问题,特别是以下错误:
Access to XMLHttpRequest at
'http://MyServer:89/Service1.svc/GetMoreData' from origin
'http://MyServer:93' has been blocked by CORS policy: Response to preflight
request doesn't pass access control check: It does not have HTTP ok status.
解决方案是为 Web 调用方法添加通配符,而不仅仅是 GET:
[OperationContract]
[WebInvoke(Method = "*", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "GetMoreData")]
System.IO.Stream GetMoreData();
我的问题:为什么一个会有这个 CORS 问题,而另一个却没有,因为它们都在同一个 IP:Port 下?
【问题讨论】:
-
嗯。并非所有请求都会触发 CORS 飞行前请求。请参阅MDN: CORS(向下滚动到“简单请求”)。我怀疑第一个请求是一个简单的请求,但第二个不是,虽然我不确定请求之间的区别是什么。
-
您的第一个请求是否以同样的方式提出?您正在指定
contentType: "application/json",,这不是“简单请求”允许的标头值之一。如果第一个请求没有那个标头,那可能是不同的。
标签: javascript wcf cors wcf-data-services