Enabling Cross-Origin Request in Web API

Enabling Cross-Origin Request in Web API

Ever got this error when building a web client making a AJAX request to another domain?

XMLHttpRequest cannot load [someurl]. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.

This post will give you some guidelines how to fix this.

Assume you have this web client code to call [someuri] to get some JSON-data.

$(document).ready(function () {
$.getJSON(uri)<br />
.done(function (data) {
// Do something with data

The problem is caused by the fact that browser security prevents a web page making a AJAX request to another domain. But there’s a solution to this problem. On the site www.asp.net, there’s a good post which explains how the enable CORS for your Web API service.

In short it means that you need to reference System.Web.Cors and System.Web.Http.Cors from your project. If you don’t have the assemblies, you can get it on NuGet.


After this on your HttpConfiguration you need to enable CORS:

// Enable Cors

The last thing you need to do is configuring CORS on your controllers by using the [EnableCors] attribute. With the [DisableCors] attribute, you can disable certain actions for CORS.

[code][EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
public class TestController : ApiController
public HttpResponseMessage PutItem(int id) { … }