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)]
public class TCCorsPolicyProvider : Attribute, ICorsPolicyProvider
{
private CorsPolicy _policy;
public TCCorsPolicyProvider()
{
_policy = new CorsPolicy
{
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);
}
public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(_policy);
}
}
Created a Factory
public class TCCorsPolicyProviderFactory : ICorsPolicyProviderFactory
{
ICorsPolicyProvider _provider;
public TCCorsPolicyProviderFactory()
{
_provider = new TCCorsPolicyProvider();
}
public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
{
return _provider;
}
}
In WebApiConfig.cs class enabled Cors
config.SetCorsPolicyProviderFactory(new TCCorsPolicyProviderFactory());
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]
public class BaseApiController : ApiController
{
public string IpAddress
{
get { return ContextHelper.GetIpAddress(); }
}
private bool _disposed;
protected virtual void Dispose(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.
What I have found so far is that the http response headers in the xmlhttp response do not contain Access-Control-Allow-Origin. However when I use HttpCient, I can see the header.