读取配置

  public class AppConfig
  {
    public static IConfigurationRoot Configuration { get; set; }

    public static IConfigurationSection GetSection(string name)
    {
      return AppConfig.Configuration?.GetSection(name);
    }

    public static T GetSection<T>(string name)
    {
      IConfigurationSection section = AppConfig.Configuration.GetSection(name);
      if (section != null)
        return section.Get<T>();
      return default (T);
    }
  }

 

 

 

自定义配置

public class AccessPolicy
    {
        public string[] Origins { get; set; }

        public bool AllowAnyHeader { get; set; }//允许的头部

        public bool AllowAnyMethod { get; set; }//允许的method:post\get……

        public bool AllowAnyOrigin { get; set; }//允许所有origin

        public bool AllowCredentials { get; set; }//允许携带cookie等信息
    }

 

Startup

 
             services.AddCors();
            ……

            AppConfig.Configuration = (IConfigurationRoot)Configuration;
            
            app.UseCors(builder =>
            {
                var policy = AppConfig.GetSection<AccessPolicy>("AccessPolicy");
                builder.WithOrigins(policy.Origins);
                if (policy.AllowAnyHeader)
                    builder.AllowAnyHeader();
                if (policy.AllowAnyMethod)
                    builder.AllowAnyMethod();
                if (policy.AllowAnyOrigin)
                    builder.AllowAnyOrigin();
                if (policy.AllowCredentials)
                    builder.AllowCredentials();
            });

appsettings.json

  "AccessPolicy": {
    "Origins": [ "*" ],
    "AllowAnyHeader": true,
    "AllowAnyMethod": true,
    "AllowAnyOrigin": true,
    "AllowCredentials": true 
  }

 

 

 

 

 

 

资料

 

https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-2.2

相关文章:

  • 2021-12-16
  • 2022-12-23
  • 2020-04-07
  • 2022-02-11
  • 2022-12-23
  • 2022-12-23
  • 2021-07-30
猜你喜欢
  • 2020-05-11
  • 2022-03-06
  • 2022-12-23
  • 2022-12-23
  • 2021-10-25
  • 2022-02-12
  • 2021-10-14
相关资源
相似解决方案