Cross-Origin Resource Sharing in WEB API

Cross-Origin Resource Sharing in Web API

In this article, we will discuss how to enable Cross-Origin Resource Sharing in Web API which allows cross-domain AJAX calls. CORS support is released with ASP.NET Web API 2. Please read our previous article before proceeding to this article as we are going to work with the same example where we discussed Calling Web API Service in a Cross Domain Using jQuery AJAX with an example.

Browsers allow a web page to make AJAX requests only within the same domain. Browser security policy prevents a web page from making AJAX requests to another domain. This is called the same origin policy. In other words, it is a known fact that browser security prevents a web page of one domain from executing AJAX calls on another domain.

CORS is a W3C standard that allows you to get away from the same origin policy adopted by the browsers to restrict access from one domain to resources belonging to another domain. You can enable CORS for your Web API using the respective Web API package (depending on the version of Web API in use).

Changes to Web API project:

Comment the following 2 lines of code in Register() method of WebApiConfig class in WebApiConfig.cs file in the App_Start folder. We added these lines in our previous articles to make ASP.NET Web API Service return JSONP formatted data

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

//config.Formatters.Insert(0, jsonpFormatter);

After comment the above two lines of code, the WebApiConfig class should look as shown below

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        //var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);
        //config.Formatters.Insert(0, jsonpFormatter);
    }
}
To allow cross-domain ajax calls by enabling CORS

Step1: Install Microsoft.AspNet.WebApi.Cors package. Execute the following command using the NuGet Package Manager Console.

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

After adding the above two lines of code, the WebApiConfig  class should as shown below.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

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

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

Step3: In the Client Application, set the dataType option of the jQuery ajax function to json dataType: ‘json’

Now run the service first and then the client application and check everything is working as expected.

Parameters of EnableCorsAttribute 

Origins:

Comma-separated list of origins that are allowed to access the resource. For example “https://www.dotnettutorials.net, https://www.something.com” will only allow ajax calls from these 2 websites. All the others will be blocked. Use “*” to allow all

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 the null or empty string to allow none

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 a null or empty string to allow none

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

If applied at a controller level then it is applicable for all methods in that controller. Call the EnableCors() method without any parameter values.

Apply the EnableCorsAttribute on the controller class

[EnableCorsAttribute("*", "*", "*")]
public class EmployeesController : ApiController
{
}

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

public class EmployeeController : ApiController
{
    [HttpGet]
    [EnableCorsAttribute("*", "*", "*")]
    public IEnumerable<Employee> GetEmployees()
    {
        EmployeeDBContext dbContext = new EmployeeDBContext();
        return dbContext.Employees.ToList();
    }
}

To disable CORS for a specific action apply [DisableCors] on that specific action In the next article, we will discuss Routing in Web API.

SUMMARY

In this article, I try to explain Cross-Origin Resource Sharing in Web API step by step with a simple example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *