The Cross-Origin request blocked error

A Cross-Origin request blocked  error happens when a web application tries to access resources – like a REST WebApi – that are placed in a different domain. For example, if we have a site my.examplesite.org  and we do an Ajax call to REST API in the domain myrestapi.org, we are going to get this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at url.

If you are developing an ASP.NET MVC project, and you are debugging from Visual Studio a couple of projects, localhost:12345 and localhost:54321, and a view at localhost:12345 tries to run this apparently innocent JavaScript code against localhost:54321, you will, once again, encounter the same  error:

$.get("localhost:54321/myAPi/getItems").success(function(result){
    $("body").append(result);
}).error(function(result){
    alert("Error");
})

The above message indicates that we have run into the Same Origin Policy, a security measure that browsers are supposed to implement to prevent third party sites from executing malicious  code.

Enabling Cross-Origin request in ASP.NET MVC projects

As I said in the second example, you can encounter this kind of error quite easily when working in a development environment. In those cases – when you know that once in production all the resources will be in the same domain – you can bypass this issue by just disabling the same origin policy in the browser.

For example, in chrome you can just close the browser and start it from the command line like this:

chromium-browser --disable-web-security --user-data-dir

On the other site, if we are developing a Rest WebAPI that needs to be accessed from a different domain, you need to configure your project to allow cross-origin request.

Adding header information in Web.config

For starters we need to configure the custom headers in the project’s web.config:

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
  • Access-Control-Allow-Origin: if we write “*” we will allow request from any site: it means that any website can make Ajax calls to the webAPI, so you´d better be sure that you really want that. To limit the access to some specific sites, write the sites separated by comas.
  • Access-Control-Allow-Headers: headers supported. Write “*” for all.
  • Access-Control-Allow-Methods: methods allowed. Once again we can use “*” to allow all.

JavaScript code for a CORS request

In the JavaScript Ajax request  we need to correctly configure the contentType:

  $.ajax({
        type: "GET",
        url: "http://192.168.1.74/mysite/api/MyServer/GetData",
        cache: false,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "json",
        success: function (data) {
            console.log(data);
        },
        error: function (data) {
            console.log(data);
        }
    });

Thanks for reading. If you find this tutorial useful you can click in the “follow” button at the end of the post to be notified of new posts.

Advertisements