【问题标题】:Use Cors based on an appSettings in .Net Core基于 .Net Core 中的 appSettings 使用 Cors
【发布时间】:2018-10-31 14:04:50
【问题描述】:

我正在将 .net 4.5.2 项目更新为 .Net 核心 web api。现在,Cors 根据 appSetting 值CorsAllowAll 设置如下:

if ((ConfigurationManager.AppSettings["CorsAllowAll"] ?? "false") == "true")
{
    appBuilder.UseCors(CorsOptions.AllowAll);
}
else
{
    ConfigureCors(appBuilder);
}

private void ConfigureCors(IAppBuilder appBuilder)
{
    appBuilder.UseCors(new CorsOptions
    {
    PolicyProvider = new CorsPolicyProvider
    {
        PolicyResolver = context =>
        {
           var policy = new CorsPolicy();
           policy.Headers.Add("Content-Type");
           policy.Headers.Add("Accept");
           policy.Headers.Add("Auth-Token");
           policy.Methods.Add("GET");
           policy.Methods.Add("POST");
           policy.Methods.Add("PUT");
           policy.Methods.Add("DELETE");
           policy.SupportsCredentials = true;
           policy.PreflightMaxAge = 1728000;
           policy.AllowAnyOrigin = true;
           return Task.FromResult(policy);
        }
    }
    });
}

如何在 .net 核心中实现相同的目标?不幸的是,我不会知道每个环境的 URL。但我确实知道对于本地、DEV 和 QA 环境,appSetting CorsAllowAll 是正确的。但是 UAT 和 PROD 环境会是错误的。

更新 我的 appSettings.json 如下:

"AppSettings": {
    ...
    "CorsAllowAll": true 
    ...
  }

【问题讨论】:

    标签: c# cors asp.net-core-webapi asp.net-core-2.1


    【解决方案1】:

    这种方法效果很好。 WithOrigins 接受 string [],因此您可以将 appsettings 值拆分为 ; 或其他值。

    appsettings.json

    
      {
      "AllowedOrigins": "http://localhost:8080;http://localhost:3000"
      }
    

    startup.cs

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext dbContext, IOptions<AppSettings> appSettings)
    
    if (!String.IsNullOrEmpty(_appSettings.AllowedOrigins))
           {
              var origins = _appSettings.AllowedOrigins.Split(";");
              app.UseCors(x => x
                        .WithOrigins(origins)
                        .AllowAnyMethod()
                        .AllowCredentials()
                        .AllowAnyHeader());
           }
    

    这种分号格式的主要原因是因为它类似于Application\Properties\launchSettings.json

    ...
    "profiles": {
            "IIS Express": {
                "commandName": "IISExpress",
                "launchBrowser": true,
                "launchUrl": "api/values",
                "environmentVariables": {
                    "ASPNETCORE_ENVIRONMENT": "Development"
                }
            },
            "Application": {
                "commandName": "Project",
                "launchBrowser": true,
                "launchUrl": "api/values",
                "applicationUrl": "http://localhost:5000;http://192.168.50.20:5000",
                "environmentVariables": {
                    "ASPNETCORE_ENVIRONMENT": "Development"
                }
            }
        }
    ...
    

    【讨论】:

    • 你也可以只使用数组:json { "AllowedOrigins": ["http://localhost:8080", "http://localhost:3000"] }
    【解决方案2】:

    在ConfigureServices方法中,定义CorsAllowAllCorsAllowSpecific两个策略

    services.AddCors(options =>
                {
                    options.AddPolicy("CorsAllowAll",
                        builder =>
                        {
                            builder
                            .AllowAnyOrigin() 
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials();
                        });                    
    
                    options.AddPolicy("CorsAllowSpecific",
                        p => p.WithHeaders("Content-Type","Accept","Auth-Token")
                            .WithMethods("POST","PUT","DELETE")
                            .SetPreflightMaxAge(new TimeSpan(1728000))
                            .AllowAnyOrigin()
                            .AllowCredentials()
                        ); 
                });
    

    可以从 Startup.cs 中的 IConfiguration 访问设置 CorsAllowAll 值。根据其值,可以在调用app.UseMvc() 之前在Configure 方法中全局设置已定义的策略之一。

    //Read value from appsettings
    var corsAllowAll = Configuration["AppSettings:CorsAllowAll"] ?? "false";
    app.UseCors(corsAllowAll == "true"? "CorsAllowAll" : "CorsAllowSpecific");
    

    【讨论】:

    • 我的 appSettings 不在根级别。它隐藏在元素“AppSettings”中。我编辑了问题以包含它..
    • 另外,我的问题不仅仅是如何获取 appSettings 值。但是如何根据 appSetting 值使用 appBuilder.useCors 呢?我无法在.net core 中使用ConfigureCors 方法..
    • 请编辑答案并使用Configuration["AppSettings:CorsAllowAll"]AppSettings.CorsAllowAll 始终为空..
    • @user007 更新了我的答案,谢谢。
    猜你喜欢
    • 2019-06-12
    • 2017-02-23
    • 2018-10-19
    • 1970-01-01
    • 2021-09-19
    • 2019-10-18
    • 2020-03-20
    • 2020-04-15
    • 2021-05-07
    相关资源
    最近更新 更多