Sunday, September 23, 2018

Cross-origin resource sharing ASP.NET Web API

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

install cors web api

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();

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

Parameters of EnableCorsAttribute 
ParameterDescription
originsComma-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
headersComma-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
methodsComma-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

The following 2 lines of code in Register() method of WebApiConfig.cs file in App_Start folder, enables CORS globally for the entire application i.e for all controllers and action methods 

EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");
config.EnableCors();

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

If applied at a controller level then it is applicable for all methods in the controller. To apply it at the controller level

1. There is no need to create an instance of EnableCorsAttribute in Register() method of WebApiConfig.cs file. Call the EnableCors() method without any parameter values.

config.EnableCors();


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

In the same manner, you can also apply it at a method level if you wish to do so.

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

When CORS is enabled, the browser sets the origin header of the request to the domain of the site making the request. The server sets Access-Control-Allow-Originheader in the response to either * or the origin that made the request. * indicates any site is allowed to make the request. 

No comments:

Post a Comment

Find the value from array when age is more than 30

 const data = [   { id: 1, name: 'Alice', age: 25 },   { id: 2, name: 'Bob', age: 30 },   { id: 3, name: 'Charlie', ...