Asp.net web api 为Web API启用多个COR

Asp.net web api 为Web API启用多个COR,asp.net-web-api,cors,Asp.net Web Api,Cors,我有一个自己编写的Web API和一个利用它的应用程序。因此,我通过向API中的控制器类添加一个头,为该应用程序添加了CORS头: [EnableCors(origins: "http://localhost:59452", headers: "*", methods: "*")] 上述措施效果良好。现在,我还希望有更多的应用程序使用该web API。我的问题是如何做到这一点?您可以通过用逗号分隔多个原点来添加它们: [EnableCors(origins: "http://localhost

我有一个自己编写的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: "*")]

Sean的回答对于简单的场景来说已经足够好了,但请注意属性参数必须是一个常量表达式,所以不能说
[EnableCors(origins:GetAllowedOrigins()…
,如果客户端更改了它们的源代码,或者需要添加一个新的源代码,则需要进行代码更改并将站点重新部署到服务器

或者,您可以在
WebApiConfig.cs
寄存器()中启用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 }
        );
    }
}

我怀疑这取决于请求者。根据,只允许一个来源。上面建议的逗号分隔字符串方法似乎适用于,但不适用于

此外,通配符(*)来源在包含cookie/凭证的情况下(至少在SPFx中)不起作用。

这是当前的方法吗?我看到其他问题/答案,用户必须创建大量代码才能实现。@Sean Bright我可以使用Originates:*“若要允许任何域?Chrome和其他人阻止此操作,将抛出一个关于多个值的错误,并且只允许一个值。是否有一种方法可以动态地将AllowedOrigins列表用于未全局启用的特定操作???@Moes您可以创建一个实现ICorsPolicyProvider的自定义属性,并从配置、数据库等中获取源你想要的y源。当列表中只允许一个源时,这是否解决了Chrome对多个源的匹配问题?