Browsed by
Tag: 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.

[code]
$(document).ready(function () {
$.getJSON(uri)<br />
.done(function (data) {
// Do something with data
});
});
[/code]

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.

Cross-Origin-Support

After this on your HttpConfiguration you need to enable CORS:

[code]
// Enable Cors
httpConfig.EnableCors();[/code]

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
{
[DisableCors]
public HttpResponseMessage PutItem(int id) { … }
}[/code]

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:

[html]
<body oncontextmenu=’return false’>
[/html]

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

[html]
<body ondragstart=’return false’ onselectstart=’return false’>
[/html]

Take into consideration that not all browsers support these features.