Gaui Gaui - 2 months ago 13
C# Question

Enable CORS in Web API 2

I have client and a server running on different ports. The server is running Web API 2 (v5.0.0-rc1).

I tried installing the Microsoft ASP.NET Web API Cross-Origin Support package and enabled it in

WebApiConfig.cs
. It gives me the
EnableCors()
function, so the package was installed correctly.

Here you can see my
Register()
function in
WebApiConfig.cs
:

public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}


GET
requests work fine. But when sending
POST
, I get the following:

OPTIONS http://localhost:19357/api/v1/rooms? 404 (Not Found) angular.js:10159
OPTIONS http://localhost:19357/api/v1/rooms? Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin. angular.js:10159
XMLHttpRequest cannot load http://localhost:19357/api/v1/rooms. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.


According to Fiddler it only sends the
OPTIONS
request. It doesn't issue the
POST
afterwards.

So I'm guessing the
config.EnableCors(cors);
in the
WebApiConfig.cs
isn't doing anything, which leads to the server denying the client/browser to send a
POST
request.

Do you have any idea how to solve this problem?

EDIT 05.09.13
This has been fixed in 5.0.0-rtm-130905

Answer

I'm most definitely hitting this issue with attribute routing. The issue was fixed as of 5.0.0-rtm-130905. But still, you can try out the nightly builds which will most certainly have the fix.

To add nightlies to your NuGet package source, go to Tools -> Library Package Manager -> Package Manager Settings and add the following URL under Package Sources: http://myget.org/F/aspnetwebstacknightly

Comments