Friday, 28 September 2018

Call an ASP.NET Web API service in a cross domain using jQuery ajax (using Jsonp or by enabling CORS)

Browsers allow a web page to make AJAX requests only within the same domain. Browser security prevents a web page from making AJAX requests to another domain.

When you are doing so,  you get the following error. To see the error launch browser tools and click on the console tab.
XMLHttpRequest cannot load http://localhost:23258/api/Employees. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:6293' is therefore not allowed access.

So this proves, browsers do not allow cross-domain ajax requests. There are 2 ways to get around this problem
Method 1: Using JSONP (JSON with Padding)

Method 2: Enabling CORS (Cross-Origin Resource Sharing)

Method 1: Using JSONP (JSON with Padding) 

Step1: To support JSONP format, execute the following command using NuGet Package Manager Console which installs WebApiContrib.Formatting.Jsonp package.
Install-Package WebApiContrib.Formatting.Jsonp

Step 2: Include the following 2 lines of code in Register() method of WebApiConfig class in WebApiConfig.cs file in App_Start folder

var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);

config.Formatters.Insert(0, jsonpFormatter);

Step 3: In the Application, set the dataType option of the jQuery ajax function to jsonp
dataType: 'jsonp'


Method 2: Enabling CORS (Cross-Origin Resource Sharing)

Step 1: Install Microsoft.AspNet.WebApi.Cors package. Execute the following command using NuGet Package Manager Console. Make sure to select your API project from "Default project" dropdown.

Install-Package Microsoft.AspNet.WebApi.Cors 

Step 2: Include the following 2 lines of code in Register() method of WebApiConfig class in WebApiConfig.cs file in App_Start folder

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");

config.EnableCors();

The Three Parameters means:
1. origins: Comma-separated list of origins that are allowed to access the resource. For example "http://www.pragimtech.com,http://www.mywebsite.com" will only allow ajax calls from these 2 websites. All the others will be blocked. Use "*" to allow all

2. headers: Comma-separated list of headers that are supported by the resource. For example "accept,content-type,origin" will only allow these 3 headers. Use "*" to allow all. Use null or empty string to allow none

3.methods: Comma-separated list of methods that are supported by the resource. For example "GET,POST" only allows Get and Post and blocks the rest of the methods. Use "*" to allow all. Use null or empty string to allow none

Step 3: In the Application, set the dataType option of the jQuery ajax function to json
dataType: 'json'


-----------------------------------------------------------------

EnableCors attribute can be applied on a specific controller or controller method. 

Then in WebApiconfig, you need only:
config.EnableCors();

 Apply the  EnableCorsAttribute on the controller class
[EnableCorsAttribute("*", "*", "*")]
public class EmployeesController : ApiController
{
}

To disable CORS for a specific action apply [DisableCors] on that specific action

Happy Coding !!!

No comments:

Post a Comment

SQL Audits

1. sys.server_audits What it is: Lists all server-level audit objects . An audit is the top-level object that defines: Where to wri...