我刚刚创建了我的第一个 WCF 服务,我想与其他客户共享它。我在 IIS、Web.config 和 Global.asax 中添加了 Access-Control-Allow-Origin
header ,但仍然不允许远程客户端访问该服务。我已经在 Chrome 和 IE(我们组织支持的浏览器)中进行了测试。我的错误是“对预检请求的响应未通过访问控制检查:请求的资源上不存在‘Access-Control-Allow-Origin’ header 。”
在 Web.config 中:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS"/>
</customHeaders>
</httpProtocol>
在 Global.asax 中:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
它们在 IIS 中:
这是尝试访问该服务的 JavaScript。它在本地工作但不能远程工作:
$.ajax({
type: "POST",
url: "http://localhost/wsSamwise/Service1.svc/GetTime",
data: '{"UserName": "' + userName + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$("#results").html(data.GetTimeResult);
console.log(data);
}
});
所有这些想法都来自各种 Stackoverflow 线程,但它们都不适合我。我错过了什么?
编辑: 我刚刚在我的本地主机和远程浏览器中检查了响应的 header 。我在本地主机的响应中看到了 Access-Control-Allow-Origin
header ,但在远程浏览器的响应中没有看到。就像没有发送一样。
来自本地主机的响应 header :
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:POST,GET,OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Allow-Origin:*
Cache-Control:private
Content-Length:82
Content-Type:application/json; charset=utf-8
Date:Thu, 05 May 2016 16:01:28 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
远程浏览器的响应:
Allow:OPTIONS, TRACE, GET, HEAD, POST
Content-Length:0
Date:Thu, 05 May 2016 16:00:09 GMT
Public:OPTIONS, TRACE, GET, HEAD, POST
Server:Microsoft-IIS/7.5
X-Powered-By:ASP.NET
编辑 2:伙计们,也许这完全是一个 IIS 问题。我刚刚向 IIS 添加了一个自定义 header 。它显示在本地主机浏览器中,但不显示在客户端上。远程浏览器中缺少 Body-Count
header ,但我在本地浏览器上看到了它。
最佳答案
确保 Ajax URL 正确。
在发布的原始代码中,我的 Ajax 请求的 URL 正在查看本地主机,而不是托管服务的机器的 FQDN。这就是问题所在。当然,如果服务未托管在 URL 上,Ajax 请求将不起作用。错误消息让我分心,以至于错过了明显而简单的解决方案。
关于c# - Access-Control-Allow-Origin 在 IIS 中,但不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37053648/