WebApi - Enable CORS for multiple Origins RRS feed

  • Question

  • 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)
                foreach (string method in allowedMethods)
                foreach (string header in allowedHeaders)
            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());

    Make sure the appropriate registration is made in Global.asax Application_Start


    I even manually applied the Policy Attribute to the my base controller

        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)
                _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.

    • Moved by Kristin Xie Thursday, October 13, 2016 5:54 AM
    Thursday, October 13, 2016 4:30 AM


  • But I get the following error (Invoking Api from Angular)


    • Proposed as answer by Kristin Xie Thursday, October 13, 2016 5:54 AM
    • Marked as answer by lalat1382 Thursday, October 13, 2016 2:47 PM
    Thursday, October 13, 2016 4:56 AM