启用Web API的多个CORS

21

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

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

上述方法运行正常。现在我还希望有更多的应用程序使用该Web API。我的问题是如何实现这一点?

3个回答

34

你可以用逗号将多个来源分隔开来进行添加:

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

2
这是当前的方法吗?我看到其他的问题/答案,用户不得不创建大量的代码才能实现它。 - Si8
@Sean Bright,我可以使用 origins:“*” 来允许任何域名吗? - TAHA SULTAN TEMURI
2
Chrome和其他浏览器会阻止此操作,因为它会抛出一个关于多个值的错误,而只允许一个。 - Connie DeCinko

28

肖恩的答案对于简单的场景已经足够好了,但请注意,属性参数必须是常量表达式,因此您不能说[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 }
        );
    }
}

2
有没有一种方法可以动态地为特定操作而不是全局启用来使用AllowedOrigins列表? - Nerdroid
@Moes,你可以创建一个实现ICorsPolicyProvider接口的自定义属性,并从配置、数据库等任何源中获取来源。 - ramseyjacob
1
这是否解决了Chrome在列表中有多个来源时只允许一个而导致的问题? - Connie DeCinko
@ConnieDeCinko 不。 - jub0bs

2
我怀疑这取决于请求者。根据这篇微软文章,只允许一个来源。建议使用逗号分隔字符串的方法在test-cors中有效,但在SPFx web part中无效。
此外,在包括cookie/凭据的情况下通配符(*)源不起作用(至少在SPFx中)。
enter image description here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接