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;
- }
- }
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();
- }
- }
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.
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)
- {
- // Web API configuration and services
- // Web API routes
- 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);
- }
- }




Khaja MoizuddinPosted Feb 6, 2019, 11:02 PM
Nice one for beginners like me. Easy to understand.