I have a WebService (.asmx) page with many functions I want to run from another webpage. The webpages I want to use ajax in to call the functions are from a different origin than the web service. When I try the following ajax call:
$.ajax({
type: "POST",
url: "http://192.168.18.218/WebSite/Pages/DBQuery.asmx/GetTestList",
crossDomain: true,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'filterID': 0
}),
dataType: "json",
success: function (data)
{
data = JSON.parse(data.d);
console.log(data);
}
});
I get the following error:
XMLHttpRequest cannot load http://192.168.18.218/WebSite/Pages/DBQuery.asmx/GetTestList. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.
I can use that exact link provided as the url on a browser on the same machine as where the web service is being hosted and everything works as expected. Using this ajax call from internet explore 11 or edge works fine as well, but when running the command from google chrome it gives the above error.
Reading up it seems like this is an issue with my web service not adding in the right fields to its response packets for CORS, so the google chrome setting catches it and throws an error. I have tried to code used for web API's to enable CORS (see the following code block).
public static void Register(HttpConfiguration config)
{
//TODO: determine acceptable origins
var corsAttr = new EnableCorsAttribute("*", "*", "*"); //accept all origins, headers, and methods
config.EnableCors(corsAttr); //enable cross origin requests
}
This did not seem to work and I cannot find documentation for this issue using web services instead of web APIs. How do I fix the web service and or ajax calls to enable CORS correctly?
EDIT Adding the following lines of code to the web config file fixes the issue with the CORS portion of the header not being added:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
</customHeaders>
</httpProtocol>
However, I still am getting a 404 error. Testing the ajax call on the machine hosting the web service, the ajax works correctly and as expected. However when running it cross origin, I get the 404 error.