In continuation of our previous article on enabling CORS support in
Step 1:
Install-Package Microsoft.AspNet.WebApi.Cors
Once you install the package, you would need to add the following in WebApiConfig.cs class:
Step 2:
using System.Web.Http;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//Enable CORS - Add this line
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Step 3: Once you enable it in
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class MyCorsPolicy : Attribute, ICorsPolicyProvider
{
private CorsPolicy _policy;
public MyCorsPolicy()
{
// Create a CORS policy.
_policy = new CorsPolicy
{
AllowAnyMethod = true,
AllowAnyHeader = true
};
// Add allowed origins.
var origins = ConfigurationManager.AppSettings["CORSOrigin"].Split(',');
foreach (var origin in origins)
{
_policy.Origins.Add(origin);
}
}
public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(_policy);
}
}
Step 4: Now we can simply use this attribute over the endpoints which need to be accessed using origins or we can do this over controller as well. The example can be like this:
[MyCorsPolicy]
public class TestController : ApiController
{
// ...
}
Here is how you can enable CORS with a dynamic list of origins.
Thanks for dropping by !!! Feel free to comment to this post or you can also drop me an email at [email protected]