Browsed by
Category: Javascript

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) { … }

Disable context menu and text selection in browser

Disable context menu and text selection in browser

When you build websites you do not always want visitors to be able to use the context menu or to be able to select the text from the site. To disable the context menu add to following code to the <body> tag of your website:

<body oncontextmenu=’return false’>

To disable text selecting, add the following code to the <body> tag:

<body ondragstart=’return false’ onselectstart=’return false’>

Take into consideration that not all browsers support these features.