I have just created my first WCF service and I would like to share it with other clients. I have added the Access-Control-Allow-Origin
header in IIS, in Web.config, and in Global.asax, but remote clients are still not allowed to access the service. I have tested in Chrome and IE (our org's supported browsers). My error is "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
In 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>
In 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();
}
}
And here they are in IIS:
Here's the JavaScript trying to access the service. It works locally but not remotely:
$.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);
}
});
All of these ideas came from various Stackoverflow threads, but none of them are working for me. What have I missed?
EDIT: I just checked out the headers for the response in my localhost vs. the remote browser. I see the Access-Control-Allow-Origin
header in the response for my localhost, but not in the response on the remote browser. It's like it's not being sent.
The response headers from my localhost:
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
The response from the remote browser:
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
EDIT 2: Guys, maybe it's an IIS issue totally. I just added a custom header to IIS. It's showing up in the localhost browser, but not on the client. The Body-Count
header is missing from remote browser, but I see it on the local browser.