【问题标题】:Permissive CORS during development, restrive CORS on production开发期间允许 CORS,生产期间限制 CORS
【发布时间】:2014-12-12 08:17:38
【问题描述】:

我们正在对 ASP.NET WebApi 2.2 进行跨站点请求。我们在WebApiConfig 中启用了 CORS:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var cors = new EnableCorsAttribute("http://www.mydomain.ca", "*", "*");
        config.EnableCors(cors);
    }
}

这在 LIVE 网站上运行良好。在开发过程中,我们需要更宽松的 CORS 设置,因为我们在 IIS 中同时托管来自多个开发环境的 WebService 和 WebClient。 IE。我们需要 new EnableCorsAttribute("*", "*", "*"); 在开发框和 LIVE 时的受限来源。

我们如何在开发和实际环境中自动从许可 CORS 切换到限制 CORS?

【问题讨论】:

    标签: asp.net asp.net-web-api cors


    【解决方案1】:

    我们目前使用内置DEBUG 常量和preprocessor directives 的方法。只要我们在 Debug 配置中运行我们的 WebApi 项目,我们就有了许可的 CORS 设置。

    定义调试:

    1. 项目 > 属性
    2. 构建
    3. 配置:调试
    4. 常规 > 定义 DEBUG 常量。

    然后使用预处理器指令:

    #if DEBUG
            var cors = new EnableCorsAttribute("*", "*", "*");
    #else
            var cors = new EnableCorsAttribute("http://www.mydomain.ca","*", "*");
    #endif
    

    【讨论】:

    • 您还可以将原始值存储在配置文件(或数据库条目)中,并为 live 和 dev 提供不同的配置文件。
    猜你喜欢
    • 1970-01-01
    • 2015-07-22
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 2022-06-25
    • 2021-01-09
    • 2021-11-23
    • 1970-01-01
    相关资源
    最近更新 更多