SCENARIO: I have two applications, one is "SPA web application" and the other one is "Web API 2.0" which is deployed on IIS 8.0 on Windows Server 2012.
ERROR: Website is accessible and working fine on the same machine but not from outside, web page is loaded properly but on ajax call to the API generates the following error...
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . This can be fixed by moving the resource to the same domain or enabling CORS.
On controller level I have added the following attribute: [EnableCors(origins: "", headers: "", methods: "*", SupportsCredentials = true)]
Also enabled it in WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional, action = "DefaultAction" }
);
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
}
web.config server configuration is like this..
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
and following is the snippet of the ajax call..
$.ajax({
type: 'get',
url: webApiUrl,
success: function (response) {
// some logic here
},
error: function (response) {
// some logic here
},
xhrFields: {
withCredentials: true
},
crossDomain: true
});
FURTHER DETAILS:
I have deployed the same website on IIS 7.5 on a Windows Server 2008 R2 and it is working fine without any issue.
Secondly I have also tried by adding following response headers in IIS 8.. Access-Control-Allow-Headers - Content-Type Access-Control-Allow-Methods - POST,GET,OPTIONS
Also tried to change following value in web.config
to
None of these have worked for me so far. Looking for further help...
FIXED :: That was just the firewall blocking the hosted web api port :(