Monday, January 25, 2016

Enabling Cross Origin Resource Sharing (CORS) in ASP.NET Web API 2

This is a quick post on how to enable CORS in Web API 2. It’s actually fairly an easy task. First you need to install Microsoft.AspNet.WebApi.Cors nuget package to the Web API project. You can do it from either of following ways.

1. Nuget Packet Manager
image
Nuget Packet Manager
2. Package Manager Console
Install-Package Microsoft.AspNet.WebApi.Cors
Then modify the Register method in WebApiConfig.cs as follows.
public static void Register(HttpConfiguration config)
{
   // enabling cross-origin requests
   config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE"));
 
   // other configuration
}
Make sure to add using System.Web.Http.Cors. You can customize the policy by setting different values to EnableCorsAttribute properties.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment