目录
配置系统
默认添加的配置提供者
加载命令行中的配置。
运行环境
读取方法
User Secrets
注意事项
Zack.AnyDBConfigProvider
案例
配置系统
默认添加的配置提供者
- 加载现有的IConfiguration。
- 加载项目根目录下的appsettings.json。
- 加载项目根目录下的appsettings.{Environment}.json。
- 当程序运行在开发环境下,程序会加载“用户机密”配置。
- 加载环境变量中的配置。
-
加载命令行中的配置。
运行环境
ASP.NET Core 会从环境变量中读取名字为ASPNETCORE_ENVIRONMENT的值。推荐值:Development(开发环境)、Staging(测试环境)、Production(生产环境)。
读取方法
app.Environment.EnvironmentName、app.Environment.IsDevelopment()……
[HttpGet]
public string Test()
{
return Environment.GetEnvironmentVariable("haha");
}
Program
app.Environment.IsDevelopment()
Controller
private readonly IWebHostEnvironment webHostEnvironment;
[HttpGet]
public string Test()
{
return webHostEnvironment.EnvironmentName;
}
User Secrets
- 把不方便放到appsettings.json中的机密信息放到一个不在项目中的json文件中。
- 在ASP.NET Core项目上单击鼠标右键,选择【管理用户机密】。
- C:\Users\用户名\AppData\Roaming\Microsoft\UserSecrets\473b31c4-af83-4603-8d28-438df885bdef
注意事项
- 供开发人员使用的,不适合在生产环境中使用。
- 仍然是明文存储。不想别人看到怎么办?Azure Key Vault、Zack.AnyDBConfigProvider等。无法完全避免。加强安全防控更重要。
- 如果因为重装、新员工等原因导致secrets.json重建,就要重新配置,麻烦。如果影响大的话,还是用集中式配置服务器。
Zack.AnyDBConfigProvider
https://github.com/yangzhongke/Zack.AnyDBConfigProviderhttps://github.com/yangzhongke/Zack.AnyDBConfigProviderhttps://github.com/yangzhongke/Zack.AnyDBConfigProviderhttps://github.com/yangzhongke/Zack.AnyDBConfigProvider
案例
- 系统的主要配置(Redis、Smtp)放到配置专用的数据库中。Zack.AnyDBConfigProvider
- 连接配置数据库的连接字符串配置在“用户机密”中。"Data Source=.;Initial Catalog=demo1;Integrated Security=SSPI;"
- 把Smtp的配置显示到界面上。
- 程序启动的时候就连接Redis,并且把Redis连接对象注册到依赖注入系统中。
secrets.json:
{
"connStr": "Data Source=.;Initial Catalog=demo1;Integrated Security=SSPI;TrustServerCertificate=true;"
}
public record SmtpSettings()
{
public string Server { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
program.cs:
//从数据库动态加载配置
builder.Host.ConfigureAppConfiguration((hostCtx, configBuilder) =>
{
//配置中读取名为"ConnStr"的连接字符串
string connStr = builder.Configuration.GetSection("ConnStr").Value;
//添加数据库配置源
configBuilder.AddDbConfiguration(() => new SqlConnection(connStr), reloadOnChange: true, reloadInterval: TimeSpan.FromSeconds(2));
});
builder.Services.Configure<SmtpSettings>(builder.Configuration.GetSection("Smtp"));
//添加Redis配置源
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
{
//在Program.cs中读取配置的一种方法
string constr = builder.Configuration.GetSection("Redis").Value;
return ConnectionMultiplexer.Connect(constr);
});
Controller:
private readonly IOptionsSnapshot<SmtpSettings> optSmtp;
private readonly IConnectionMultiplexer connectionMultiplexer;
public Test(IOptionsSnapshot<SmtpSettings> optSmtp, IConnectionMultiplexer connectionMultiplexer)
{
this.optSmtp = optSmtp;
this.connectionMultiplexer = connectionMultiplexer;
}
[HttpGet]
public string Demo1()
{
var ping = connectionMultiplexer.GetDatabase(0).Ping();
return optSmtp.Value.ToString() + ":" + ping;
}