2016-02-02 46 views
4

多個CORS我有一個Web API,我寫的,並利用它一個應用程序。所以我加CORS標題爲應用程序了通過我的API內將報頭添加到控制器類:啓用的Web API

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

上述工作得很好。現在我也想要更多的應用程序使用該Web API。我的問題是我如何做到這一點?

回答

8

您可以用逗號分隔添加多個來源:

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

這是當前的方法嗎?我看到其他問題/答案,用戶必須創建大量代碼才能實現它。 – Si8

+0

@Sean Bright我可以使用起源:「*」來允許任何域名? – DumpsterDiver

12

肖恩的答案是簡單的場景不夠好,但請注意一個屬性參數必須是常量表達式,所以你不能說[EnableCors(origins:GetAllowedOrigins()...如果客戶端更改其來源或需要添加新的來源,則需要更改代碼並將網站重新部署到服務器。

作爲替代方案,你可以在WebApiConfig.csRegister() method.This使CORS使CORS全球,但允許你動態設置允許origins.This讓你保持在例如數據庫允許起源的列表,並且可以更新根據需要。您仍然需要在任何更改後重新啓動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 } 
     ); 
    } 
} 
+2

有沒有一種方法可以動態地使用AllowedOrigins列表來進行不是全局啓用的特定操作? – Moes