Implementation Of Cross Origin Request In ASP.NET Web API 2 Using AngularJS

The article is designed from the very beginning of Cross Origin Resource Sharing (CORS) implementation.

What is CORS?

The major concept of CORS is getting data from a WEB API which has been hosted to another server. Firstly, we imagine two applications- WebClient and WebService and both of these are not in the “same origin” (We’ll discuss about same origin and different origin below). In this situation if we send a request from the WebClient to WebService in order to get some response data then we’ll receive some invalid request warning. It happens because two different application from two different origin cannot communicate frequently with each other. We can handle this issue through implementing CORS. It allow us to send request and get response between two applications which are of different origin.

Same Origin- If the two url have identical schemes, hosts and port then they have the same origin.
These two url have the same origin-

http://localhost:2179
http://localhost:2179/Contact/Dashboard


And these two url have the different origin-

http://localhost:2101
http://localhost:2179


Origin

Implementation

Step 1: In Visual Studio create a Web API project.

Empty website

Step 2: Add a class named User with the following properties.

  1. public class User  
  2. {  
  3.     public int ID { getset; }  
  4.     public string Name { getset; }  
  5.     public string Email { getset; }  
  6.   
  7. }  
Step 3: Add an API controller with the following code.
  1. using ClientApp.Models;  
  2. using System.Collections.Generic;  
  3. using System.Net;  
  4. using System.Net.Http;  
  5. using System.Web.Http;  
  6.   
  7. namespace WebServiceApp.Controllers  
  8. {  
  9.     public class UserController : ApiController  
  10.     {  
  11.         public HttpResponseMessage GetInfo()  
  12.         {  
  13.             var res = new List<User>() {  
  14.                 new User { ID = 1, Name = "Gopal", Email = "[email protected]" },  
  15.                 new User { ID = 2, Name = "Nayan", Email = "[email protected]" },  
  16.                 new User { ID = 3, Name = "Shuvo", Email = "[email protected]" }  
  17.             };  
  18.             return Request.CreateResponse(HttpStatusCode.OK, res);  
  19.         }  
  20.     }  
  21. }  
Now we can run the application locally. In order to verify the Web API is working I navigated to the following URL: http://localhost:8595/api/User in my localhost and got the document tree of User object as response.
  1. <ArrayOfUser xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/ClientApp.Models">  
  2.     <User>  
  3.         <Email>[email protected]</Email>  
  4.         <ID>1</ID>  
  5.         <Name>Gopal</Name>  
  6.     </User>  
  7.     <User>  
  8.         <Email>[email protected]</Email>  
  9.         <ID>2</ID>  
  10.         <Name>Nayan</Name>  
  11.     </User>  
  12.     <User>  
  13.         <Email>[email protected]</Email>  
  14.         <ID>3</ID>  
  15.         <Name>Shuvo</Name>  
  16.     </User>  
Step 4: Now create another Web Application. Here I have created an MVC application.

MVC

Step 5: Install AngularJS using nuget package manager console.

Install-Package angularjs

Step 6: Now replace the Index.cshtml view under Home by the following code.
  1. <script src="~/Scripts/angular.min.js"></script>  
  2. <div class="row" ng-app="myApp" ng-controller="userCtrl">  
  3.     <br />  
  4.     <div class="col-md-12">  
  5.         <nav class="navbar navbar-default">  
  6.             <div class="container-fluid">  
  7.                 <div class="navbar-header">  
  8.                     <div class="container">  
  9.                         <br />  
  10.                         <button class="btn btn-danger" ng-click="sendRequest()">Get Response</button>  
  11.                     </div>  
  12.                     <div class="container">  
  13.                         <h2>CORS Response</h2>  
  14.                         <table class="table table-bordered">  
  15.                             <thead>  
  16.                                 <tr>  
  17.                                     <th>ID</th>  
  18.                                     <th>Name</th>  
  19.                                     <th>Email</th>  
  20.                                 </tr>  
  21.                             </thead>  
  22.                             <tbody>  
  23.                                 <tr ng-repeat="u in users">  
  24.                                     <td>{{u.ID}}</td>  
  25.                                     <td>{{u.Name}}</td>  
  26.                                     <td>{{u.Email}}</td>  
  27.                                 </tr>  
  28.                             </tbody>  
  29.                         </table>  
  30.                     </div>  
  31.                 </div>  
  32.             </div>  
  33.         </nav>  
  34.     </div>  
  35. </div>  
  36.   
  37. <script>  
  38.     var app = angular.module('myApp', []);  
  39.     app.controller('userCtrl', function ($scope, $http) {  
  40.         $scope.sendRequest = function () {  
  41.             $http.get("http://localhost:8595/api/User/GetInfo")  
  42.         .success(function (response) {  
  43.             $scope.users = response;  
  44.         }).error(function (jqXHR, textStatus, errorThrown) {  
  45.             console.log(jqXHR.responseText || textStatus);  
  46.         });  
  47.         };  
  48.     });  
  49. </script>  
Step 7: Set both the application as Startup project.

Run the project and press the Get Response button. This time we’ll get the following js error.

Code

CORS is not implemented yet to the API project and also it’s header is not defined.

Step 8: Using package manager console install CORS to the API project.

Install-Package Microsoft.Asp.Net.WebApi.Cors

Step 9: Open the App_Start/WebApiConfig.cs file and add the following code to the WebApiConfig.Register method.
  1. using System.Web.Http;  
  2.   
  3. namespace WebServiceApp  
  4. {  
  5.     public static class WebApiConfig  
  6.     {  
  7.         public static void Register(HttpConfiguration config)  
  8.         {  
  9.             //CORS config  
  10.             config.EnableCors();  
  11.             // Web API configuration and services  
  12.   
  13.             // Web API routes  
  14.             config.MapHttpAttributeRoutes();  
  15.   
  16.             config.Routes.MapHttpRoute(  
  17.                 name: "DefaultApi",  
  18.                 routeTemplate: "api/{controller}/{id}",  
  19.                 defaults: new { id = RouteParameter.Optional }  
  20.             );  
  21.         }  
  22.     }  
  23. }  
Step 10: Add the [EnableCors] attribute to the UserController.
  1. using ClientApp.Models;  
  2. using System.Collections.Generic;  
  3. using System.Net;  
  4. using System.Net.Http;  
  5. using System.Web.Http;  
  6. using System.Web.Http.Cors;  
  7.   
  8. namespace WebServiceApp.Controllers  
  9. {  
  10.     [EnableCors(origins: "http://localhost:8578", headers: "*", methods: "*")]  
  11.     public class UserController : ApiController  
  12.     {  
  13.         public HttpResponseMessage GetInfo()  
  14.         {  
  15.             var res = new List<User>() {  
  16.                 new User { ID = 1, Name = "Gopal", Email = "[email protected]" },  
  17.                 new User { ID = 2, Name = "Nayan", Email = "[email protected]" },  
  18.                 new User { ID = 3, Name = "Shuvo", Email = "[email protected]" }  
  19.             };  
  20.             return Request.CreateResponse(HttpStatusCode.OK, res);  
  21.         }  
  22.     }  
  23. }  
Now run the project once again and get the desired response.

Cors

In my next article I’ll show how CORS works with its different implementations.