我有一个自己编写的Web API和一个使用它的应用程序。因此,我通过向API中的控制器类添加标头为该应用程序添加了CORS标头:
[EnableCors(origins: "http://localhost:59452", headers: "*", methods: "*")]
上述方法运行正常。现在我还希望有更多的应用程序使用该Web API。我的问题是如何实现这一点?
我有一个自己编写的Web API和一个使用它的应用程序。因此,我通过向API中的控制器类添加标头为该应用程序添加了CORS标头:
[EnableCors(origins: "http://localhost:59452", headers: "*", methods: "*")]
上述方法运行正常。现在我还希望有更多的应用程序使用该Web API。我的问题是如何实现这一点?
你可以用逗号将多个来源分隔开来进行添加:
[EnableCors(origins: "http://localhost:59452,http://localhost:25495,http://localhost:8080", headers: "*", methods: "*")]
肖恩的答案对于简单的场景已经足够好了,但请注意,属性参数必须是常量表达式,因此您不能说[EnableCors(origins:GetAllowedOrigins()...
如果客户端更改其来源或您需要添加新的来源,则需要进行代码更改并重新部署站点到服务器。
作为替代方案,您可以在WebApiConfig.cs
Register()
方法中启用CORS。这将全局启用CORS,但允许您动态设置允许的来源。例如,这使您可以在数据库中维护允许的来源列表,并根据需要进行更新。您仍然需要在任何更改后重新启动Web应用程序,但不需要进行任何代码更改:
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 }
);
}
}