Handling Cross-Domain Call In ASP.NET Web API

Introduction

 
What is a "Same Origin Policy"?
      
Browsers allow a web page to make the AJAX request only within the same origin. The browser security prevents a web page from the cross-origin AJAX request. This phenomenon is known as "same origin policy".
 
This we can overcome using
  1. JSONP while making the AJAX call
  2. Enabling CORS in ASP.NET WEB API
What is JSONP?
   
JSONP is nothing but JSON with padding, which basically is used while making a Cross-Domain request. It bypasses the cross-site scripting limitation by the browser, and it doesn't use XMLHttpRequest object. Instead, it uses the <script> tag.
 
What is CORS?
 
Cross-Origin Resource Sharing (CORS) manages the cross-origin requests. Unlike same-origin policy, CORS allows making a request from one origin to another. CORS allows the servers to specify who can access the resource on the server from outside.
 
The origin is made up of three parts - the protocol, host, and the port number
 
What will we learn here?
  • Calling ASP.NET WEB API Service using AJAX JSONP
  • How to use JSONP formatter in ASP.NET WEB API
  • Enabling CORS in ASP.NET WEB API
Software Used
  • Visual Studio 2017
  • POST MAN

Calling ASP.NET WEB API Service Using Normal AJAX Call

    
Create a Web API project

Step 1
 
Open Visual Studio, click on NEW ->Project. Select ASP.NET Web Application template under Web, as shown in the below figure.
 
Handling Cross Domain Call In ASP.NET WEB API 

Step 2
 
Select WEB API template and click OK.
 
Handling Cross Domain Call In ASP.NET WEB API 

Step 3
 
Let’s create a model. In my case, I named it as Customer.cs.
   
Model -> Customer.cs
  1. public class Customer  
  2.     {  
  3.         public int CustomerID { getset; }  
  4.         public string CustomerName { getset; }  
  5.   
  6.         public Customer(int customerID, string customerName)  
  7.         {  
  8.             CustomerID = customerID;  
  9.             CustomerName = customerName;  
  10.         }  
  11.     }  
Step 4
 
Create a Controller. Right-click on controllers folder and go to Add -> Controller.
 
Controller->CustomerController.cs 
  1. public class CustomerController : ApiController  
  2.   {  
  3.       public List<Customer> GetCustomers()  
  4.       {  
  5.           List<Customer> customers = new List<Customer>();  
  6.           customers.Add(new Customer(1, "Arun"));  
  7.           customers.Add(new Customer(2, "Raj"));  
  8.           return customers.ToList();  
  9.       }  
  10.   
  11.   }  
Step 5
 
Let’s test this API using Postman.
 
Handling Cross Domain Call In ASP.NET WEB API 
From the above figure, you can notice we have received the list of customers as a JSON response based on our request.
 
Step 6
 
Let’s create another web project to consume the API. Right-click on the solution, Add-> New Project -> select ASP.NET Web application template. In my case, I named it as WebForm.
 
Handling Cross Domain Call In ASP.NET WEB API
 
Step 7
 
Select the Web Form template and click OK.  
 
Handling Cross Domain Call In ASP.NET WEB API
 
Solution structure:
 
Handling Cross Domain Call In ASP.NET WEB API
 
Step 8
 
Right-click on the WebForm project and add a new HTML file.

Customer.html 

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <title></title>  
  6.     <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>  
  7. </head>  
  8. <body>  
  9.     <button id="btnajax">Click Me</button>  
  10.     <script>  
  11.         $(document).ready(function () {  
  12.             $("#btnajax").on("click"function (e) {  
  13.                 $.ajax({  
  14.                     type: "GET",  
  15.                     url: "http://localhost:60347/api/Customer/GetCustomers",  
  16.                     dataType: "json",  
  17.                     success: function (data) {  
  18.                         console.log(data)  
  19.                     }  
  20.                 })  
  21.             })  
  22.               
  23.         })  
  24.     </script>  
  25. </body>  
  26. </html>  
From the above code, it is obvious that we have a button control. When the button is clicked, it will trigger the AJAX call which sends a request to our WEB API  to get a customer's details.

Now, when we click on the button, we will get an error message in the console of the developer tools, as shown in the below figure. The message tells us that the Cross-origin call is not allowed because of the same origin policy since both the web applications are running in different domains.
 
WEB API application is running on http://localhost:60347/ and the Web Form project is running on http://localhost:60766
This can be overcome by using the JSONP.
 
Handling Cross Domain Call In ASP.NET WEB API
Step 9
 
Right-click on Web API project -> Manage NuGet Packages- > Install WebApiContrib.Formatting.Jsonp package, as shown in the below figure
 
Handling Cross Domain Call In ASP.NET WEB API 
 
Step 10
 
Open WebApiConfig.cs file and add the below code, 
  1. public static class WebApiConfig  
  2.   {  
  3.       public static void Register(HttpConfiguration config)  
  4.       {  
  5.           // Web API configuration and services  
  6.   
  7.           // Web API routes  
  8.           config.MapHttpAttributeRoutes();  
  9.            
  10.           config.Routes.MapHttpRoute(  
  11.               name: "DefaultApi",  
  12.               routeTemplate: "api/{controller}/{id}",  
  13.               defaults: new { id = RouteParameter.Optional }  
  14.   
  15.           );  
  16.           var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);  
  17.           config.Formatters.Insert(0, jsonpFormatter);  
  18.       }  
  19.   }  

The above code config.Formatters.Insert(0, jsonpFormatter)  will inject the jsonp formatter in HTTP Configuration 

Step 11
 
Modify the Javascript code with datatype as jsonp in ajax request,
  1. $(document).ready(function () {  
  2.           $("#btnajax").on("click"function (e) {  
  3.               $.ajax({  
  4.                   type: "GET",                     
  5.                   url: "http://localhost:60347/api/Customer/GetCustomers",  
  6.                   dataType: "jsonp",  
  7.                   success: function (data) {  
  8.                       console.log(data)  
  9.                   }  
  10.               })  
  11.           })  
  12.   
  13.           
  14.             
  15.       })  
Run the project.
 
Click on the button; now you can see the Customer list in the console, as shown in the below figure,
 
Handling Cross Domain Call In ASP.NET WEB API

Enabling the CORS in ASP.NET WEB API


Step 1
 
Go to the Web API project, right click on the project and select Manage NuGet Package Manager, install Microsoft.AspNet.WebApi.Cors

Step 2
 
Add the below code in WebApiConfig file Register method, 
  1. public static void Register(HttpConfiguration config)  
  2.        {  
  3.            // Web API configuration and services  
  4.   
  5.            // Web API routes  
  6.            config.EnableCors();  
  7.            config.MapHttpAttributeRoutes();  
  8.             
  9.            config.Routes.MapHttpRoute(  
  10.                name: "DefaultApi",  
  11.                routeTemplate: "api/{controller}/{id}",  
  12.                defaults: new { id = RouteParameter.Optional }  
  13.   
  14.            );  
  15.        }  
EnableCors() method will enable the cross origin request.
 
Step 3
 
In controller add Enable CORS attribute in Global level, so that all the action in this controller can be accessed from http://localhost:60766
  1. [EnableCors(origins: "http://localhost:60766", headers: "*", methods: "*")]  
  2.     public class CustomerController : ApiController  
  3.     {  
  4.        
  5.         public List<Customer> GetCustomers()  
  6.         {  
  7.             List<Customer> customers = new List<Customer>();  
  8.             customers.Add(new Customer(1, "Arun"));  
  9.             customers.Add(new Customer(2, "Raj"));  
  10.             return customers.ToList();  
  11.         }  
  12.   
  13.     }  

Step 4

Let's update the javascript code with normal ajax call where the datatype as json 
  1. $(document).ready(function () {  
  2.           $("#btnajax").on("click"function (e) {  
  3.               $.ajax({  
  4.                   type: "GET",                     
  5.                   url: "http://localhost:60347/api/Customer/GetCustomers",  
  6.                   dataType: "jsonp",  
  7.                   success: function (data) {  
  8.                       console.log(data)  
  9.                   }  
  10.               })  
  11.           })  
  12.       
  13.       })  
Step 5
 
Run the application
 
Handling Cross Domain Call In ASP.NET WEB API
 
Now, the GetCustomers action can be accessed through http://localhost:60766. To make it available for all the origins, we need to do the following update in code.
 
We need to set * to origin in CustomerController.cs.
  1. [EnableCors(origins: "*", headers: "*", methods: "*")]  
  2.     public class CustomerController : ApiController  
  3.     {  
  4.        
  5.         public List<Customer> GetCustomers()  
  6.         {  
  7.             List<Customer> customers = new List<Customer>();  
  8.             customers.Add(new Customer(1, "Arun"));  
  9.             customers.Add(new Customer(2, "Raj"));  
  10.             return customers.ToList();  
  11.         }  
  12.   
  13.     }  
Run the application.
 
Handling Cross Domain Call In ASP.NET WEB API
 
From the above figure, you can notice the Access Control Allow Origin is set with *. Now, it can be consumed from any origin. 
 

Conclusion


We have learned how to handle the cross-origin requests in ASP.NET Web API using JSONP and by enabling the CORS. I hope you have enjoyed this article. Your valuable feedback, questions, or comments about this article are always welcomed.


Similar Articles