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 }
);
}
}