代码改变世界

.Net Core: 跨域Cros概要

2019-04-24 11:45  huoit  阅读(307)  评论(0)    收藏  举报

读取配置

  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