I have a C# Web API project. I created a Controller using the Web API 2 standard. I am trying to enable CORS on only one action, this is what I have:
namespace MyProject.Controllers
{
public class MyControllerController : ApiController
{
// POST api/mycontroller
[EnableCors("http://link.myurl.com", "*", "*")]
public bool Post(MyCustomObject customObject)
{
// Function that returns Bool
return myFunction(customObject);
}
}
}
My WebApiConfig.cs looks like this:
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Ignore Null values on JSON Returns
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore };
Here is the Cross-Domain AJAX call:
$.ajax({
type: "POST",
url: 'http://myurl.com/api/mycontroller',
data: JSON.stringify({ Type: 'TextHere', OtherInfo: 'TextHere' }),
contentType: "application/json",
success: function (data) {
}
});
Based off tutorials such as this one: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#how-it-works, I should have everything properly setup.
I continue to get the following error in Chrome:
XMLHttpRequest cannot load http://myurl.com/api/mycontroller. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://link.myurl.com' is therefore not allowed access.
When I take a look at the calls using Fiddler, I notice that the Pre-flight Origin check goes through fine with Status 200, but when the actual call is made it returns 500.
Interestingly enough, the transactions are committed to the database even though the call failed. It's almost like the Pre-flight Origin check is running through the code when it should just be checking for Allow Origin.
I've tried adding the following to web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://link.myurl.com" />
</customHeaders>
</httpProtocol>
<system.webServer>
If I leave the [EnableCors] line, then I get an error that two values are specified (http://link.myurl.com) when there can only be one. If I remove the [EnabledCors] line, I get the original error.
If you can't already tell, I'm at a loss here. Ironically it is working (database actions being committed), but the browser thinks its not working and never accepts the JSON return data.
HELP?