.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
1、如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!
2、欢迎各位转载,但是未经作者本人同意,转载文章请在文章页面明显位置标明作者和原文连接,否则保留追究法律责任的权利。
作者博客: http://www.cnblogs.com/xmai/