I have been trying to enable CORS for multiple origins for my API without any success.
Here is what I have done.
Created a CORS Policy
[AttributeUsage(AttributeTargets.All,AllowMultiple=false,Inherited=true)]publicclassTCCorsPolicyProvider:Attribute,ICorsPolicyProvider{privateCorsPolicy _policy;publicTCCorsPolicyProvider(){ _policy =newCorsPolicy{SupportsCredentials=true};string[] allowedOrigins ="john.doe,ava.wise".Split(',');string[] allowedMethods ="GET,POST,PUT,OPTIONS".Split(',');string[] allowedHeaders ="Content-Type,Origin,Authorization,Accept".Split(',');// Add allowed origins.foreach(string origin in allowedOrigins) _policy.Origins.Add(origin);foreach(string method in allowedMethods) _policy.Methods.Add(method);foreach(string header in allowedHeaders) _policy.Headers.Add(header);}publicTask<CorsPolicy>GetCorsPolicyAsync(HttpRequestMessage request,CancellationToken cancellationToken){returnTask.FromResult(_policy);}}
Created a Factory
publicclassTCCorsPolicyProviderFactory:ICorsPolicyProviderFactory{ICorsPolicyProvider _provider;publicTCCorsPolicyProviderFactory(){ _provider =newTCCorsPolicyProvider();}publicICorsPolicyProviderGetCorsPolicyProvider(HttpRequestMessage request){return _provider;}}
In WebApiConfig.cs class enabled Cors
config.SetCorsPolicyProviderFactory(newTCCorsPolicyProviderFactory()); config.EnableCors();
Made sure the appropriate registration is made in Global.asax Application_Start
GlobalConfiguration.Configure(WebApiConfig.Register);
When the above did not work I even manually applied the Policy Attribute to the my base controller from which all other controllers inherit
[TCCorsPolicyProvider]publicclassBaseApiController:ApiController{publicstringIpAddress{get{returnContextHelper.GetIpAddress();}}privatebool _disposed;protectedvirtualvoidDispose(bool disposing,Action disposeAction){if(!_disposed){if(disposing){ disposeAction();}} _disposed =true;}}
But I get the following error (Invoking Api from Angular)
XMLHttpRequest cannot load hqidwtcdwa01/api/localizations/reloadCache. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'ava.wise' is therefore not allowed access. The response had HTTP status code 401.
hqidwtcdwa01 is the destination and ava.wise is the origin.