Use Cors based on an appSettings in .Net Core

南笙酒味 提交于 2020-02-05 04:21:09

问题


I am updating a .net 4.5.2 project to .Net core web api. Right now, the Cors is setup as below based on an appSetting value 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);
        }
    }
    });
}

How can I achieve the same in .net core? Unfortunately, I won't be knowing the URLs of each environment. But I do know that for Local, DEV and QA environments, the appSetting CorsAllowAll is true. But the UAT and PROD environments it would be false.

UPDATE My appSettings.json is like below:

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

回答1:


In ConfigureServices method, define two policies namely CorsAllowAll and CorsAllowSpecific

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

The setting CorsAllowAll value can be accessed from IConfiguration in Startup.cs. Depending on its value, it is possible to set one of the defined policies globally in Configure method, before calling app.UseMvc().

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



回答2:


This method works great. WithOrigins accepts a string [] so you can just split an appsettings value by ; or something else.

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


来源:https://stackoverflow.com/questions/50456918/use-cors-based-on-an-appsettings-in-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!