基于 .Net Core 中的 appSettings 使用 Cors

Use Cors based on an appSettings in .Net Core

我正在将 .net 4.5.2 项目更新到 .Net 核心网站 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 
    ...
  }

在 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");

这个方法很管用。 WithOrigins 接受一个 字符串 [] 所以你可以用 ; 或其他东西分割一个 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"
            }
        }
    }
...