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 works on principle of same origin policy.
- Same origin policy is a sandboxing mechanism which ensures that script downloaded from server A cannot talk to server B.
- Reason is that we don’t want to attack some other server using JS on our behalf.
- The matching of the server A and server B is based on protocol, domain and port. If any of these is different the call will be unsuccessful. Same is true with 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() { new Person() { FirstName = "Vikram", LastName = "Chaudhry" }, new Person() { FirstName = "Martin", LastName = "Flower" } } ; var response = this.Request.CreateResponse >(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"; }Index
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.
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.
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() { new Person() { FirstName = "Vikram", LastName = "Chaudhry" }, new Person() { FirstName = "Martin", LastName = "Flower" } } ; var response = this.Request.CreateResponse >(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
- install the nuget package install-package Microsoft.AspNet.WebApi.
- Add EnableCors attribute on the controller.
- 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() { new Person() { FirstName = "Vikram", LastName = "Chaudhry" }, new Person() { FirstName = "Martin", LastName = "Flower" } } ; var response = this.Request.CreateResponse >(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.
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.
Kuldeep Yadav says
Great stuff …!!!
Vikram Chaudhary says
Thank you Dear 🙂
Vikram Chaudhary says
Thank you Dear 🙂