How to enable CORS on your Web API

In order to enable CORS in the Web API, you should install the Microsoft.AspNet.WebApi.Cors package, which is

If you are wondering how to enable CORS in your Web API, you should install the Microsoft.AspNet.WebApi.Cors package, which is available on NuGet.

In Visual Studio, select Library Package Manager from the Tools menu, and then select Package Manager Console. Write the following command in the console window:

In the Solution Explorer, expand the WebApi project. Open the file App_Start/WebApiConfig.cs, and add the following code to the method WebApiConfig.Register.

Then add the attribute [EnableCors] to the desired controller:

For the origins parameter, use the URL that you want to let the controller execute. This allows the cross-domain requests from a client with another domain.

Scope Rules of [EnableCors]

CORS may be enabled per action, per controller or globally for all the controllers of the Web API.

Per Action
In order to enable CORS for only one action, set the attribute [EnableCors] above the action method. Here you can see one example.

Per Controller
In order to enable CORS at controller level, you should set the attribute [EnableCors] above the name of the class. When CORS in enabled in a controller, it is applied for all the actions on the controller. To disable CORS for one action, set the parameter [DisableCors] on the action. For example:

Globally
In order to enable CORS for all the controllers in the application, pass an EnableCorsAttribute instance to the EnableCors method of the settings:

If the attribute is applied more than once, the order of precedence will be:

  1. Action
  2. Controller
  3. Global

For further information, visit the official ASP.NET Web API web page http://www.asp.net/web-api

Are you looking for the best technical solution for your company? Contact us for more information and we will get back to you!

Share this articleShare on LinkedInTweet about this on TwitterShare on FacebookShare on Google+Email this to someone
Go Back