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
- JSONP while making the AJAX call
- 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.
Step 2
Select WEB API template and click OK.
Step 3
Let’s create a model. In my case, I named it as Customer.cs.
Model -> Customer.cs
- public class Customer
- {
- public int CustomerID { get; set; }
- public string CustomerName { get; set; }
-
- public Customer(int customerID, string customerName)
- {
- CustomerID = customerID;
- CustomerName = customerName;
- }
- }
Step 4
Create a Controller. Right-click on controllers folder and go to Add -> Controller.
Controller->CustomerController.cs
- public class CustomerController : ApiController
- {
- public List<Customer> GetCustomers()
- {
- List<Customer> customers = new List<Customer>();
- customers.Add(new Customer(1, "Arun"));
- customers.Add(new Customer(2, "Raj"));
- return customers.ToList();
- }
-
- }
Step 5
Let’s test this API using Postman.
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.
Step 7
Select the Web Form template and click OK.
Solution structure:
Step 8
Right-click on the WebForm project and add a new HTML file.
Customer.html
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
- <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
- </head>
- <body>
- <button id="btnajax">Click Me</button>
- <script>
- $(document).ready(function () {
- $("#btnajax").on("click", function (e) {
- $.ajax({
- type: "GET",
- url: "http://localhost:60347/api/Customer/GetCustomers",
- dataType: "json",
- success: function (data) {
- console.log(data)
- }
- })
- })
-
- })
- </script>
- </body>
- </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.
Step 9
Right-click on Web API project -> Manage NuGet Packages- > Install WebApiContrib.Formatting.Jsonp package, as shown in the below figure
Step 10
Open WebApiConfig.cs file and add the below code,
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
-
-
-
- config.MapHttpAttributeRoutes();
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
-
- );
- var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);
- config.Formatters.Insert(0, jsonpFormatter);
- }
- }
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,
- $(document).ready(function () {
- $("#btnajax").on("click", function (e) {
- $.ajax({
- type: "GET",
- url: "http://localhost:60347/api/Customer/GetCustomers",
- dataType: "jsonp",
- success: function (data) {
- console.log(data)
- }
- })
- })
-
-
-
- })
Run the project.
Click on the button; now you can see the Customer list in the console, as shown in the below figure,
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,
- public static void Register(HttpConfiguration config)
- {
-
-
-
- config.EnableCors();
- config.MapHttpAttributeRoutes();
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
-
- );
- }
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,
- [EnableCors(origins: "http://localhost:60766", headers: "*", methods: "*")]
- public class CustomerController : ApiController
- {
-
- public List<Customer> GetCustomers()
- {
- List<Customer> customers = new List<Customer>();
- customers.Add(new Customer(1, "Arun"));
- customers.Add(new Customer(2, "Raj"));
- return customers.ToList();
- }
-
- }
Step 4
Let's update the javascript code with normal ajax call where the datatype as json
- $(document).ready(function () {
- $("#btnajax").on("click", function (e) {
- $.ajax({
- type: "GET",
- url: "http://localhost:60347/api/Customer/GetCustomers",
- dataType: "jsonp",
- success: function (data) {
- console.log(data)
- }
- })
- })
-
- })
Step 5
Run the application
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.
- [EnableCors(origins: "*", headers: "*", methods: "*")]
- public class CustomerController : ApiController
- {
-
- public List<Customer> GetCustomers()
- {
- List<Customer> customers = new List<Customer>();
- customers.Add(new Customer(1, "Arun"));
- customers.Add(new Customer(2, "Raj"));
- return customers.ToList();
- }
-
- }
Run the application.
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.