X

Subscribe To Our Mailing List

P.S I will never spam you...100% GUARANTEED!

Monday, October 5, 2015

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. (Reason: CORS header 'Access-Control-Allow-Origin' missing).


Problem Statement

When working with AngularJS and Web API this issue can be seen. Lets create a sample Web API and AngularJS project to reproduce this issue and lets find the solution to this as well.

Demo

First create a sample Web API project and add - "ProductController.cs" file -

public class ProductController : ApiController
{
 private List _products;

 public ProductController()
 {
  _products = new List() { new Product() { ProductId = 1, CategoryId=100, ProductName ="Prod1"},
   new Product() { ProductId = 2, CategoryId=100, ProductName ="Prod2"}};
 }

 // GET api/product
 public List Get()
 {
  return _products;
 }

 // GET api/product/5
 public Product Get(int id)
 {
  return _products.First(a => a.CategoryId == id);
 }

 // POST api/product
 public void Post([FromBody]Product prod)
 {
  _products.Add(prod);
 }

}

Now lets create a sample html page for AngularJS application. Here lets main concentrate on the service part, which is doing a AJAX call to the Web API service -


myApp.service('sampleService', function ($http) {
 this.getProducts = function () {
  return $http.get('http://localhost:53308/api/Product/'); // Different domain call.
 }
});


As we can see in the above code. Web API running in the different domain than the client application. Below is the screenshot of error -



Solution

As a part of solution add the "<customHeaders>" tag to web config like below -

<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>


Hope this post is useful. Please put your thoughts in the comment section below.





No comments:

Post a Comment

Comments Section