Recently we just added the support for CORS in Web API. You can find more information on this from our Channel 9 video. Although the feature is checked in, it’s not officially released yet. Nevertheless, you can try it out using our signed nightly builds. In this post, I’ll give you a step by step walkthrough on how to upgrade your MVC 4 project and install the Microsoft.AspNet.WebApi.Cors package from the nightly builds.
Step 1. Create a new Web API project
Start with a new Web API template.
Step 2. Uninstall the Microsoft.AspNet.Mvc.FixedDisplayModes package.
This package is not needed and will prevent you from updating to the latest nightly build.
Step 3. Install Microsoft.AspNet.WebApi.Cors package from the nightly builds
See the instruction here on using the nightly builds. Once the package source is set, you should be able to see the CORS package (Microsoft.AspNet.WebApi.Cors).
There’s one more step you need to follow (Step 4) before running the application. Otherwise you’ll see the following error.
Step 4. Fix up the binding redirects in web.config
You can just replace the existing <assemblyBinding> with the following.
After that, your application should run just fine.
Trying it out
To make a quick cross-origin request you can just browse to the test client that I have hosted on Azure: http://webapisample.azurewebsites.net/Help/Api/GET-api-Values
Click on “Test API”, paste the full URI to your Web API and click “Send”. You’ll see that the request failed because your Web API doesn’t have CORS enabled by default.
Now, let’s enable CORS for your APIs by calling config.EnableCors(new EnableCorsAttribute()) as shown in the sample below. This will enable CORS for all your controllers and allow all origins. See the feature spec for more information.
Update 04/26/13: The EnableCorsAttribute now requires the allowed origins, headers and methods in the constructor. To allow all, use EnableCorsAttribute(“*”, “*”, “*”).
After that, the same request will succeed and we get back the response.
Few notes when testing this with IE
- IE does not consider the port to be a part of the Security Identifier (origin) used for Same Origin Policy enforcement. This means if you have test client on localhost:3030 and the Web API on localhost:8080, IE won’t be making a cross-origin request
- When using the test client hosted on azure, you might need to add it to the trusted site to call the Web API hosted on your local machine (localhost)
Hope you find this useful!