根据.Net Core中的appSettings使用Cors

时间:2018-05-21 21:36:39

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

我正在将.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。但我知道,对于Local,DEV和QA环境,appSetting CorsAllowAll都是正确的。但是UAT和PROD环境是错误的。

更新 我的appSettings.json如下所示:

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

2 个答案:

答案 0 :(得分:2)

此方法效果很好。 WithOrigins 接受字符串[] ,因此您可以通过;或其他方式分割应用设置值。

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());
       }

答案 1 :(得分:1)

在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中的CorsAllowAll访问设置IConfiguration值。根据其值,可以在调用Configure之前在app.UseMvc()方法中全局设置一个已定义的策略。

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