Dot Net For All

Understanding and Enabling CORS on Web api

In this article I will help you to understand the CORS (Cross origin resource sharing). And we will understand enabling cors on a web api which I have developed as an example for this article.

What is CORS?

CORS Example

Service Side

Suppose we have a web api service which is returning some data on the GET request. Please check the code below.

 public class PersonController : ApiController
    {
        public HttpResponseMessage Get()
        {
            var personList = new List<Person>() { new Person() { FirstName = "Vikram", LastName = "Chaudhry" },
                new Person() { FirstName = "Martin", LastName = "Flower" }
            } ;
            var response = this.Request.CreateResponse<IList<Person>>(personList);            
            return response;

        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

If I execute the above api in browser I can see the below result. As we can see the API is getting executed at the location “http://localhost:59578”. This can be different in your machine.

Client Side

Below is the code for client side. This is a simple MVC application. In the Index.cshtml I have added the below code.

@{
    ViewBag.Title = "Index";
}
<head>
    <script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
    <script>
        $(document).ready(function () {
            $('#click').click(function () {   
                $.ajax({
                    url: 'http://localhost:59578/api/Person',
                    data: '',
                    datatype: 'json',
                    success: function (data) {
                        $.each(data, function (index, value) {
                            $('#mytable').append("<tr><td>" + value.FirstName + "</td><td>" + value.LastName + "</td><tr>");
                        });
                    },
                    error: function (xhr)
                    {
                        alert(xhr.statusText);
                    }
                })
            });
        })
    </script>
</head>
<h2>Index</h2>
<input type="button" id="click" value="Click Me" style="height: 20px; width: 70px" />
<table id="mytable"></table>

In the above code I am executing an ajax call to the service on the click of the button. If I run the application, I will be navigated to the Index  method of the Home controller. We can see the below page in the browser.

 

Web api call from MVC client

 

As we can see in the above figure, the client is running on the different port from the web api though both are running on the same machine.

If I click on the button. I will get the “failure” pop up in the window. To see the error I can open the Developer Tools window of the chrome browser by pressing ‘F12’ and go to the console I can see the below error.

CORS Error from Web Api

 

The above error clearly says that access is not allowed to the particular resource.

Enabling CORS on Web API

There are two ways by which we can enable CORS on the Web API.

Adding “Access-Control-Allow-Origin” as Response Header

One way to achieve the CORS is by adding the response header for the Origin domain as shown in the below code. In the below code I am the header with the origin value by taking it our from the request.

        public HttpResponseMessage Get()
        {
            var personList = new List<Person>() { new Person() { FirstName = "Vikram", LastName = "Chaudhry" },
                new Person() { FirstName = "Martin", LastName = "Flower" } } ;

            var response = this.Request.CreateResponse<IList<Person>>(personList);
            response.Headers.Add("access-control-allow-origin", 
                ((string[])(this.Request.Headers.Where(item => item.Key == "Origin").ElementAt(0).Value))[0]);

            return response;

        }

This may not be the best solution. But it can be helpful if we want allow CORS for any particular Action on the web api.

Adding EnableCors Attribute

  1. install the nuget package install-package Microsoft.AspNet.WebApi.
  2. Add EnableCors attribute on the controller.
  3. Add the config.EnableCors(); in the WebApiConfig.cs.

The changed code of the controller class enabling CORS

 [EnableCors("*", "*", "*")]
    public class PersonController : ApiController
    {
        public HttpResponseMessage Get()
        {
            var personList = new List<Person>() { new Person() { FirstName = "Vikram", LastName = "Chaudhry" },
                new Person() { FirstName = "Martin", LastName = "Flower" } } ;

            var response = this.Request.CreateResponse<IList<Person>>(personList);           

            return response;

        }
    }

In the above code I have enabled the CORS for all the Origins, headers, and methods. If you want to enable it for any of these specific values you can provide them in the comma separated list replacing *.

If I call the web api after doing the changes I can see the result at the client side as shown in the below figure.

CORS enabled web api call

 

Conclusion:

In this article I have discussed about the CORS. I have explained with examples different ways of enabling cors and call the web api from the MVC C# application.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview