【发布时间】:2019-10-03 07:15:00
【问题描述】:
我在前端有 Ajax 调用,我正在通过 ajax 调用调用 WCF 服务,但是 ajax 调用有一些添加标头,这就是为什么第一次预检 OPTIONS 请求被引发并且由于“url”而下降的原因已被 cors 政策阻止。
我已经在我的 web.config 文件中添加了下面的代码,但它仍然可以工作。
<system.webServer>
<security>
<requestFiltering>
<verbs>
<add verb="OPTIONS" allowed="true" />
<add verb="POST" allowed="true" />
<add verb="GET" allowed="true" />
<add verb="DELETE" allowed="false" />
</verbs>
</requestFiltering>
</security>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="accept, cache-control, content-type, authorization, context" />
</customHeaders>
</httpProtocol>
</system.webServer>
$.ajax({
async: true,
type: "POST",
headers: {
'Authorization': 'Basic ' + btoa(BasicAuth),
'Context': 'Context' + btoa(ContextHeader)
},
contentType: "application/json; charset=utf-8",
data: '{"Id": "' + Id + '" }',
url: URL + "/MethodName",
success: function (result) {
response = result;
if (response == true)
Xrm.Page.data.refresh(true);
$('#msgDiv').fadeOut('slow');
},
error: function (status) {
console.log(status.status);
$('#msgDiv').fadeOut('slow');
Configurations.OnFailure(status);
}
});
上面是我用javascript写的代码。
在 HTTP 上调用它工作正常。但在 HTTPS 上调用它不工作。
我在控制台上收到如下错误
enter code here
OPTIONS https://abc/xyz 400(错误请求)
从源 'https://Localhost' 访问 XMLHttpRequest 在 'https://abc/xyz' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态
【问题讨论】:
-
“下面的代码”中没有任何内容,您应该将它放在问题中 - 但您似乎还没有配置 IIS 来处理 OPTIONS 请求
-
我已经检查了 iis 以处理选项请求
-
我可以看到请求过滤中允许的 OPTIONS 动词。
-
是的,但是您没有显示的代码(服务器端代码)显然并未真正处理 OPTIONS 请求(只是因为 IIS 允许它,并没有使其 处理 i>)
-
您能否通过使用 PostMan Tool over Https 获得正确的响应?此外,我将以下代码添加到 global.asax 文件的 Application_beginrequest 事件中。 if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS") { Response.End(); }
标签: javascript c# ajax wcf