To enable Cross-Domain request, you must allow it on server side as well as client side.
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.
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.
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;
}
}
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.');
}
});
}
});
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.
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.