How to enable cors in WebApi to handle request from different subdomains?
I created my webApi which was hosted on different subdomain. When I was trying to access it through Angular, I was getting error with Access-Control-Allow-Origin. In my research I found I need to enable Cors to handle cross origin requests. Below is the steps to enable cors in WebApi.
Enabling CORS in WebApi
- Install
Install-Package Microsoft.AspNet.WebApi.Cors
- Update WebApiConfig.cs
using System.Web.Http;
namespace WebService
{
public static class WebApiConfig {
public static void Register(HttpConfiguration config)
{
EnableCrossSiteRequests(config);
config.Routes.MapHttpRoute(
name: “DefaultApi”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }
);
}
private static void EnableCorsForCrossSiteRequests(HttpConfiguration config)
{
var cors = new EnableCorsAttribute(
origins: “*”,
headers: “*”,
methods: “*”);
config.EnableCors(cors);
}
}
}
In above code The EnableCorsAttribute is a globally scoped CORS attribute.
- Update your controller
[EnableCors(origins: “https://test.desibanjara.com”, headers: “*”, methods: “*”)]
[RoutePrefix(“api/ desibanjara “)]
public class TestController : ApiController
{
}