Is there a way to dynamically update the list of allowed sources in CORS Web API

I am trying to enable CORS for specific domains in my .Net Web API application and can do this in a Start application through this code.

public static void Register(HttpConfiguration config) { //below comma separated string is built from database var domains = "http://www.myfirstdomain.com,http://www.myseconddomain.co.uk .... about 130 domains more.."; config.EnableCors(new EnableCorsAttribute(domains, "*", "*")); 

However, if new domains are added while the application is live, they will not be allowed to send the cross-domain until the application pool is reused and this list is created again.

Is there a way to update this list for the life of my application? I know that I can recycle the application pool periodically, but this can lead to delays in some requests that I could ideally handle.

I know that I can enable this in the controller method, that is ..

 [EnableCors("http://domain1.com,http://domain2.com", "*", "*")] public HttpResponseMessage PostAsync([FromBody] MyRequest myRequest) { 

However, again, a parameter separated by a comma must be declared as a constant and therefore cannot be dynamic.

Am I missing something obviously obvious, or can anyone think of a decent way to do this?

EDIT

Here is my attempt to write my own custom EnableCors attribute.

 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] public class EnableCorsByDomainAttribute : Attribute, ICorsPolicyProvider { private readonly CorsPolicy _policy; public EnableCorsByDomainAttribute() { _policy = new CorsPolicy { AllowAnyMethod = true, AllowAnyHeader = true }; var originsString = "http://www.test1.com,http://www.test2.com"; if (!String.IsNullOrEmpty(originsString)) { foreach (var origin in originsString.Split(',')) { _policy.Origins.Add(origin); } } } public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken) { return Task.FromResult(_policy); } } 

Then I decorated the controller method with

 [EnableCorsByDomain] 
+7
ajax cors asp.net-web-api
source share
1 answer

Yes, the CORS web API provides an extension point for such a scenario. For more information, see the section " Implementing a Custom ICorsPolicyProvider " in the following Web API specification functional document.

http://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API&referringTitle=Specs

+6
source share

All Articles