Cross-Origin Resource Sharing in WEB API

Cross-Origin Resource Sharing in Web API

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

  1. What are the same-origin policy and default behavior of browsers in AJAX Requests?
  2. What is CORS?
  3. How to enable CORS in Web API?
  4. Understanding the Parameters of EnableCorsAttribute.
  5. How to use EnableCors attribute at the Controller and action method level?
  6. How to Disable CORS?
What are the same-origin policy and default behavior of browsers in AJAX Requests?

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.

What is CORS?

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:

Delete the following 2 lines of code in the 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);

Your WebApiConfig class should look as shown below.

Cross-Origin Resource Sharing in Web API

How to enable CORS in Web API?

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: A 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: A 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: A 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

How to use EnableCors attribute at the Controller and action method level?

It is also possible to apply the EnableCors attribute either at the controller level or at the action method level. 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, I am going to discuss Routing in Web API. Here, 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 needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

3 thoughts on “Cross-Origin Resource Sharing in WEB API”

  1. Hello,
    Your guides are splendid! In this particular article it is not clear to me whether I need to enable Cors in the MVC and in the Web API EmployeeService projects simultaneously?

Leave a Reply

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