Web API 2 – Cross-Origin Resource Sharing (CORS) Support

Web API 2 has the CORS support  out of the Box. Its available as attributes called EnabledCors and DisableCors.

As an attribute it can be extended based on our requirement,  we can easily bring the feature to allow or disallow specific external sites to share resource.

Cross-Origin attribute can be enabled globally on WebApiConfig as below.Install the Microsoft ASP.NET Web API 2.2 Cross-Origin from Nuget.

var apicors = new EnableCorsAttribute("*", "*", "GET,POST");
config.EnableCors(apicors);

We can set the properties of the attribute by initializing EnableCorsAttribute, helps us to specify the origin sites, headers and methods.And also has option to specify wild char with “*”, to allow all or everyone.

Other way to implement it, in the Controller level applying as attribute to Controller or Action Methods. This has the flexibility to EnableCors to controller and DisableCors to selective action within the Controller.