enable cors with dynamic list of origins

Enable CORS with a dynamic list of origins

In continuation of our previous article on enabling CORS support in webapi, I will be blogging today on how to enable CORS with a dynamic list of origins. If a client is trying to access endpoints located in some other server, and if the server has not enabled CORS support to the domain of client CORS issue occurs. In order to support multiple origins in WebAPI application in C#, we need to do the following.

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 
        // Web API routes 
            name: "DefaultApi", 
            routeTemplate: "api/{controller}/{action}/{id}", 
            defaults: new { id = RouteParameter.Optional } 

Step 3: Once you enable it in webapiconfig, you need to create a Attribute for custom CORS policy which would take origins as input from web.config and would enable those origins to access the endpoints. The custom CORS policy attribute may look like this:

[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) 
    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:

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]