Calling ASP.NET Web API Service Cross Domain Using AJAX

Introduction

This article explains how to call ASP.NET Web API in the cross domain, using AJAX in a simple step by step way. We can deploy and use our Web API in the cross-domain. While calling cross domain, we will be facing some issues. This article explains how to resolve and how to use Web API in the cross domain. Please read the previous part of this article in the link given below before reading this article.

Calling Web API in Cross Origin

Web page and ASP.NET Web API Services hosted in the different domains are called cross-origin. For example, a Web Application hosted in http://test.com and ASP.NET Web API Service hosted in http://testAPI.com. We can see the URL for the Web Application and ASP.NET Web API looks as shown below in the cross domain or cross-origin.



JSONP

JSONP is a JSON with padding. While accessing the data, using AJAX call, we cannot access the data cross-domain because of security reasons. JSONP is used to access the data in the cross domain. JSON returns a JSON-formatted object only. JSONP returns a JSON-formatted object, which is wrapped inside a function call. The example given below differentiates it for JSON and JSONP.

JSON format 

  1. {  
  2.     “Id”             :  “1”,  
  3.         “Name”     :  “Vignesh”,  
  4.     “Address”: “India”,  
  5. }   

JSONP format 

  1. callbackFunction ({  
  2.     “Id”             :  “1”,  
  3.         “Name”     :  “Vignesh”,  
  4.     “Address”: “India”,  
  5. })   

Steps to create cross-origin or cross domain

Step 1

This step is a continuation of previous part of the article. Please find the links given below for first part of the article.

Step 2

Remove the HTML page in our solution files. Now, add a new project in the same solution. Right click on the Solution Explorer, go to “Add” and click new project.


Step 3

Now, select The Web. Under Web, select ASP.NET Web Application in Add New Project Windows and give the project name. Finally, click OK.



Now “New ASP.NET Project - Customers” Window will open. Now, select Web Forms and click OK. Afterwards, add the new project in the solution. We can see the two projects in the single solution.



Step 4

Now, right click on Customer project adds “Customer.html” page in Customers project. Now, copy the same code from “WebAPIsameDomain” project “Customers.html” page and paste it to “Customer” project “Customers.html” page.


Step 5

Now, build our solutions and run ASP.NET Web API Service and Customers.html page. We can see the different port number. The screenshot given below shows it differently.

http://localhost:49352/api/Demo - ASP.NET Web API URL.



http://localhost:52273/Customers.html - Web Page URL.



After building our solution and running “http://localhost:49352/api/Demo” for ASP.NET Web API and running “http://localhost:52273/Customers.html” for our Web page, now click Get button but we don't get any result because of the security problem in cross-origin.

ASP.NET Web API Service returns JSON format data. It is not supported in the cross domain because of the security issue. If we go to developer tool, we can see the error. The error is “XMLHttpRequest cannot load http://localhost:49352/api/Demo. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:52273' is therefore not allowed access.”



To fix this security issue, we need to use JSONP in AJAX, so that ASP.NET Web API Service returns JSONP format. First, enable JSONP in our “Customers” project.

Step 6

We need to install JSONP package in our solution. Go TOOLS àNuGet Package Manager à Manage NuGet Packages for Solutions. We can see it looks like the screenshot given below.


Step 7

After opening Manage NuGet Packages Window, type “JSONP” in the search box, search it. Now, we can get the “WebApiContrib.Formatting.Jsonp” package and click the install button. Read the description columns and one can learn about the package.


After clicking install, it will open Select Project Window, which looks, as shown below. Now, click the check box in which the project needs this package and click OK. Afterwards, click OK and then click I accept button and after some moments; it will be installed. Finally, close Manage NuGet Packages Window.


Step 8

Go to the “WebAPIsameDomain” and go to the “App_Start” folder, followed by going to the “WebApiConfig.cs” file. Now, write the code mentioned below to enable JSONP format in Register method. The code given below is used to convert JSON to JSONP format.

We are using “JsonpMediaTypeFormatter” class, which is used to convert JSON to JSONP. It's namespace is “WebApiContrib.Formatting.Jsonp”.


Code to convert JSONP 

  1. Using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Web.Http;  
  6. using Microsoft.Owin.Security.OAuth;  
  7. using Newtonsoft.Json.Serialization;  
  8. using WebApiContrib.Formatting.Jsonp;  
  9.   
  10. namespace WebAPIsameDomain  
  11. {  
  12.     public static class WebApiConfig  
  13.     {  
  14.         public static void Register(HttpConfiguration config)  
  15.         {  
  16.             // Web API configuration and services  
  17.             // Configure Web API to use only bearer token authentication.  
  18.             config.SuppressDefaultHostAuthentication();  
  19.             config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));  
  20.   
  21.             // Web API routes  
  22.             config.MapHttpAttributeRoutes();  
  23.   
  24.             config.Routes.MapHttpRoute(  
  25.                 name: "DefaultApi",  
  26.                 routeTemplate: "api/{controller}/{id}",  
  27.                 defaults: new { id = RouteParameter.Optional }  
  28.             );  
  29.   
  30.             var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);  
  31.             config.Formatters.Insert(0,jsonpFormatter);  
  32.         }  
  33.     }  
  34. }   

Step 9

Now, go to HTML page and change the data type from JSON to JSONP, which looks, as shown below.



Now build and run the project we get the correct output which looks like the below screenshot.


We are calling ASP.NET Web API Service from http://localhost:49352/api/Demo to http://localhost:52273/Customers.html Web Application. Here, we can see the different port numbers in the URL. It is called cross-origin. If it uses a different domain, like calling ASP.NET Web API Service from http://testAPI.com/api/Demo to http://test.com/Customers.html Web Application is called cross domain.

Conclusion

This article explained about calling ASP.NET Web API in the cross-origin, using AJAX by following some steps. This helps new learners and developers. This article and previous parts of the article clearly explain about the same and cross-origin in ASP.NET Web API.


Similar Articles