21

I have a Web API I wrote and one application utilizing it. SO I added CORS header for that applicaiton by adding a header to the controller class within my API:

[EnableCors(origins: "http://localhost:59452", headers: "*", methods: "*")]

The above worked fine. Now I also want more applications consuming that web API. My question is how do I make this happen?

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Coding Duchess
  • 6,445
  • 20
  • 113
  • 209

3 Answers3

34

You can add multiple origins by separating them with commas:

[EnableCors(origins: "http://localhost:59452,http://localhost:25495,http://localhost:8080", headers: "*", methods: "*")]
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
28

Sean's answer is good enough for simple scenarios but please note that an attribute argument must be a constant expression, so you can't say [EnableCors(origins:GetAllowedOrigins()... If a client changes their origin or you need to add a new one you will need to make code changes and re-deploy site to the server.

As an alternative you can enable CORS in the WebApiConfig.cs Register() method.This enables CORS globally but allows you to dynamically set the allowed origins.This allows you to maintain a list of allowed origins in a database for example and can be updated as needed.You would still need to restart the web application after any changes but no code changes will be necessary:

public static class WebApiConfig
{
    private static string GetAllowedOrigins()
    {
        //Make a call to the database to get allowed origins and convert to a comma separated string
        return "http://www.example.com,http://localhost:59452,http://localhost:25495";
    }

    public static void Register(HttpConfiguration config)
    {
        string origins = GetAllowedOrigins();
        var cors = new EnableCorsAttribute(origins, "*", "*");
        config.EnableCors(cors);

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Denys Wessels
  • 16,829
  • 14
  • 80
  • 120
2

I suspect it depends on the requester. According to this MS article, only one origin is allowed. The comma delimited string approach suggested above appears to work in test-cors, but not in an SPFx web part.

Also the wildcard (*) origin does not work in cases where cookie/credentials are included (at least in SPFx).
enter image description here

Tracy
  • 680
  • 7
  • 16