Enable CORS in Web API 2

Gaui picture Gaui · Sep 4, 2013 · Viewed 106.8k times · Source

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

Sudhanshu Mishra picture Sudhanshu Mishra · Dec 8, 2014

CORS works absolutely fine in Microsoft.AspNet.WebApi.Cors version 5.2.2. The following steps configured CORS like a charm for me:

  1. Install-Package Microsoft.AspNet.WebApi.Cors -Version "5.2.2" // run from Package manager console
  2. In Global.asax, add the following line: BEFORE ANY MVC ROUTE REGISTRATIONS

    GlobalConfiguration.Configure(WebApiConfig.Register);
    
  3. In the WebApiConfig Register method, have the following code:

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

In the web.config, the following handler must be the first one in the pipeline:

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

In the controller derived from ApiController, add the EnableCorsAttribute:

[EnableCors(origins: "*", headers: "*", methods: "*")] // tune to your needs
[RoutePrefix("")]
public class MyController : ApiController

That should set you up nicely!