Browsed by
Category: Language

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, 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: “”, headers: “*”, methods: “*”)]
public class TestController : ApiController
public HttpResponseMessage PutItem(int id) { … }

API Billionaires Club

API Billionaires Club

This simple infographic shows that Twitter serves more API calls than Facebook and Google combined. I wonder what this graph will look like when Google comes with it’s API for Google+.

Google hasn’t released an API for Google+ yet. But there’s a mailing list you can sign-up for to receive more information in the future.