Please enable Javascript for better experience...
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. This can be fixed by moving the resource to the same domain or enabling CORS.
By Big | Mar 28, 2015 | In Tips | Total Views [ 15767 ]
(8 Like)
Rate

To enable Cross-Domain request, you must allow it on server side as well as client side.

The Problem

I created a Web API and trying to call it from a angular js application through ajax call. Suddenly it started throwing Cross-Origin Request (CORS). I searched googled for more than 2-3 hours to get appropriate solution but was unable to get. I tried almost every example I found on different-different sites but did not get any success.

A Quick Solution

Any time you are dealing with Cross-Domain Request or CORS you may face any of these error. Either you will see "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:52924/api/values/3. This can be fixed by moving the resource to the same domain or enabling CORS." or you may see "405 Method Not Allowed" in header or "Access-Control-Allow-Origin" error. To overcome this you must define headers to allow access-control like Access-Control-Allow-Origin or Access-Control-Allow-Headers. Let see this with an example.

Web API Controller

Add a web api controller and put code for GET.

    public class ValuesController : ApiController
    {
        // GET api/values/5
        public string Get(int id)
        {
            return "value:" + id;
        }
    }

AngularJS Code

Create a angular js controller and put this code into this to make a call to Web API.

app.controller('TestController',function ($scope) {
    $scope.TestAPICall = function () {
        $.ajax({
            url: "http://localhost:52924/api/values/3",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            success: function (res) {
                debugger;
                alert('API called successfully.');
            },
            error: function (res) {
                debugger;
                alert('Error while calling API.');
            }
        });
    }
});

HTML

Bind method created above to button and click to see result.

<div ng-controller="TestController">
    <input type="submit" ng-click="TestAPICall()" value="Call API" />
 </div>

You will see below error.

CORS error

Adding custom header to Web API Web.Config

Add custom header to web.config file in <system.webServer> tag to allow Cross-Domain Request (CORS).

  <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>

You will find API is calling successfully with no error. Hope this can help you.

Share this

About the Author

Big
Rahul Jha (Big)
Founder, Developer dotnet-concept.com
Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment