How to enable Cross Origin Resource Sharing in ASP.NET WEB API 2?

There is a restriction named the same-origin policy that all the browsers have that prevents a web page from making AJAX requests to other domain for security reasons. As this prevents a malicious site from reading sensitive data from another site. However, sometimes due to the requirement of your application, you might want to let other sites call you web API. In this post I’ll tell you how to enable Cross Origin Resource Sharing in ASP.NET WEB API 2.

What is CORS?

Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than earlier techniques such as JSONP. This tutorial shows how to enable CORS in your Web API application.
W3C

If I make a call from one domain (empty web app) to another (web API app) using JavaScript, the response that I receive using Chrome browser is:

The network tab that records this request says it has been cancelled. In the console tab I can see following error: XMLHttpRequest cannot load http://localhost:14541/api/products. Origin http://localhost:47854 is not allowed by Access-Control-Allow-Origin.

How does it work?

When a browser makes a request to another domain, it will send along an origin header with the value of the domain that it came from. So, if you are on www.siddharthpandey.net and this download a script which tries to make a connection to some other site, say www.sp.com, the site making request will set the Origin header as http://www.siddharthpandey.net. If the other site allows this, it will send back an HTTP message with a header named Access-Control-Allow-Origin header with value http://www.siddharthpandey.net which provides access to the resource.

If that header is not present, then the browser will not allow the JavaScript to receive that response.

Tools/Packages

  • ASP.NET WEB API V2.2
  • Visual Studio
  • Microsoft.AspNet.WebApi.Cors Nuget Package

Let us fix this issue. Install the nuget package above in your web api project. After the installation, it is very easy to use it in project.

Enable CORS at app level/scope

Enable CORS support for all the controllers in your application by modifying your app’s WebApiConfig.cs file to add following code:

The code above just creates an attribute that lives inside System.Web.Http.Cors namespace with following parameters:

  • origin: to allow request from particular origin. * can also be used to allow requests from any origin.
  • headers: any required header that server application need to see.  * can also be used to allow anything.
  • methods: to allow only mentioned HTTP methods. If more than one use GET,POST with comma as a delimiter or use * to allow any HTTP methods.

Enable CORS at controller level/scope

The attribute mentioned above is used for this case as well but at controller level like this:

After a successful rebuild, I can now get the a collection of products from the api hosted in another domain. Now, server finds the Origin header in request, check if it violates any constraint for CORS setup. If everything matches, then it returns a response with Access-Control-Allow-Origin with the domain as value which is then read by the browser.

This comes really handy if someone has a JavaScript client-side app (or single page application, SPA) and wants to interact with other applications hosted on a different domain then follow this post to enable Cross Origin Resource Sharing in ASP.NET WEB API 2.

Siddharth Pandey

Siddharth Pandey is a Software Engineer with thorough hands-on commercial experience & exposure to building enterprise applications using Agile methodologies. Siddharth specializes in building, managing on-premise, cloud based real-time standard, single page web applications (SPAs). He has successfully delivered applications in health-care, finance, insurance, e-commerce sectors for major brands in the UK. Other than programming, he also has experience of managing teams, trainer, actively contributing to the IT community by sharing his knowledge using Stack Overflow, personal website & video tutorials.

You may also like...

Advertisment ad adsense adlogger