为Web API启用多个CORS

Cod*_*ess 13 cors asp.net-web-api

我有一个我编写的Web API和一个使用它的应用程序.我通过在API中向控制器类添加标头为该应用程序添加了CORS标头:

[EnableCors(origins: "http://localhost:59452", headers: "*", methods: "*")]
Run Code Online (Sandbox Code Playgroud)

以上工作正常.现在我还想要更多的应用程序使用该Web API.我的问题是如何实现这一目标?

Sea*_*ght 21

您可以使用逗号分隔多个来源:

[EnableCors(origins: "http://localhost:59452,http://localhost:25495,http://localhost:8080", headers: "*", methods: "*")]
Run Code Online (Sandbox Code Playgroud)

  • 这是当前方法吗?我看到其他问题/答案,用户必须在其中创建大量代码才能实现。 (2认同)
  • Chrome 和其他人阻止了这一点,抛出关于多个值的错误,并且只允许一个。 (2认同)

Den*_*els 21

Sean的答案对于简单的场景来说已经足够好但是请注意,属性参数必须是一个常量表达式,所以你不能说[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 }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法动态使用AllowedOrigins列表的特定操作未全局启用??? (2认同)