I have a question regarding the implementation of cors in a ASP.NET Web API. The reason I am turning to SO is that I've tried searching everywhere, and found a lot of tutorials and answers, but none of those seem to work for me.
Setup:
- Web Application (HTML5, JS) running on XAMPP (192.168.1.101:8080)
- API (ASP.net) running on IIS Express (Integrated with VS2013) (192.168.1.101:52126)
The web application makes ajax calls to the API as shown in the code block below.
$.ajax({
data: JSON.stringify(data),
type: 'POST',
url: 'http://localhost:52126/api/controller/action',
dataType: 'json',
contentType: 'application/json',
processData: false,
headers:
{
"Authorization": "Basic Base64Encrpytion"
},
success: function(data)
{
// Handle success
},
error: function(data)
{
// Handle error
}
});
This all works perfectly in localhost including OPTION preflight. But when I start the web application from a other device in the same local network, the preflight fails and ofcourse if the preflight fails the rest of the calls get canceled as well.
Error:
When trying to query the API from another device (192.168.1.100) in the same network using the web application the following responses are generated:
Console
OPTIONS http://192.168.1.101:52126/api/controller/action 400 (Bad Request)
OPTIONS http://192.168.1.101:52126/api/controller/action No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.101:8080/' is therefore not allowed access.
XMLHttpRequest cannot load http://192.168.1.101:52126/api/controller/action. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.101:8080/' is therefore not allowed access.
Response Header
Connection: close
Content-Length: 334
Content-Type: text/html; charset=us-ascii
Date: Wed, 05 Mar 2014 09:29:46 GMT
Server: Microsoft-HTTPAPI/2.0
The response header does contain the Access-Control-Allow-Origin "*" header when testing the web application and API on localhost.
Solutions I have tried:
Adding the code below to each class that needs to be reached from outside the domain.
[EnableCors(origins: "*", headers: "*", methods: "*")]
Adding the code below to the Web.config file.
<httpprotocol>
<customheaders>
<add name="Access-Control-Allow-Origin" value="*"></add>
</customheaders>
</httpprotocol>
Adding the code below to the WebApiConfig file.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
Adding the code below to the applicationhost.config
<binding protocol="http" bindingInformation="192.168.1.101:52126:*" />
The following setting is set to true
jQuery.support.cors = true
I have also tried to override the preflight handler, but that seemed to fail as well.