技术平台
- 版本:.NET6
- 开发工具: Visual Studio 2022
配置系统顺序
在ASP.NET Core中的默认配置顺序如下,后者会覆盖前者(如果存在值的情况下)。
- 现有的IConfiguration(一般不需要在这个前面加)
- 项目根目录下appsettings.json
- 项目根目录下appsettings.{Environment}.json
- 用户机密
- 环境变量
- 命令行参数
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//运行环境读取方法
if (app.Environment.EnvironmentName == "AlbertTest")
{
Console.WriteLine(app.Environment.EnvironmentName);
}
配置系统综合案例
- 功能需求:
- 系统的主要配置放到配置专用的数据库中
- 连接配置数据库的连接字符串配置在用户机密中
- 把Smtp的配置显示到界面上
- 程序启动就连接Redis,并把Redis连接对象注入到依赖注入的系统中
- 实现 在appsettings.json或者其他机密文件中添加数据库连接字符串
"SqlServer": {
"ConnectStr": "Server = .; Database = AlbertConfigDb; Trusted_Connection = True;MultipleActiveResultSets=true;Connect Timeout=500"
}
安装Zack.AnyDBConfigProvider包-安装System.Data.SqlClient包,在Program中添加如下代码:
//Zack.AnyDBConfigProvider里面的GetConnectionString读取的字符串是配置文件中的
//而不是数据库中的,连接上数据库后,AddDbConfiguration才是从数据库中读取Json
//这里Host和WebHost一个是主机一个是通用主机
//如果想要启用builder.Configuration.GetConnectionString("con");
//则需要在appsettings.json中配置“ConnectionStrings:con":"xxx"
builder.WebHost.ConfigureAppConfiguration((hostCtx, configBuilder) => {
var env = hostCtx.HostingEnvironment;
var connStr = builder.Configuration.GetValue<string>("SqlServer:ConnectStr");
configBuilder.AddDbConfiguration(() =>
new SqlConnection(connStr),
reloadOnChange: true,
reloadInterval: TimeSpan.FromSeconds(2),
tableName: "ProduceToolConfig");
//开发模式下,保存项目程序集到用户机密
if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
configBuilder.AddUserSecrets(appAssembly, optional: true);
}
}
});
安装StackExchange.Redis包,这样就可以直接启动Redis了
//AddDbConfiguration之后即可从数据库中拿取Json对了
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
{
//在Program.cs中读取配置的一种方法
var connStr = builder.Configuration.GetValue<string>("RedisServer:Configuration");
return ConnectionMultiplexer.Connect(connStr);
});
读取数据库中配置信息,直接绑定到SmtpSettings类上
public class SmtpSettings
{
public string ServerName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
//配置选项:Smtp 注意这里的根是appsettings.json
builder.Services.AddOptions().Configure<SmtpSettings>(smtp => builder.Configuration.GetSection("SmtpSettings").Bind(smtp));
//调用
using AlbertZhao.cn.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
namespace AlbertZhao.cn.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class SmtpController : ControllerBase
{
private readonly ILogger<SmtpController> logger;//日志服务
private readonly IOptionsSnapshot<SmtpSettings> options;//配置选项服务
private readonly IConnectionMultiplexer connectionMultiplexer;//Redis服务
public SmtpController(ILogger<SmtpController> logger, IOptionsSnapshot<SmtpSettings> options, IConnectionMultiplexer connectionMultiplexer)
{
this.logger = logger;
this.options = options;
this.connectionMultiplexer = connectionMultiplexer;
}
[HttpGet]
public ActionResult<SmtpSettings?> GetSmtpInfo()
{
logger.LogInformation("开始获取数据");
return new SmtpSettings() { ServerName = options.Value.ServerName ,
UserName = options.Value.UserName ,
Password = options.Value.Password
};
}
[HttpGet]
public ActionResult<string?> GetRedisInfo()
{
logger.LogInformation("开始测试Redis");
var ping = connectionMultiplexer.GetDatabase(0).Ping();
return ping.ToString();
}
}
}
附录-工具推荐Notion
下图是个人改版的程序员版本Notion笔记,其中有各个季度的目标制定、年度目标进度追踪、Github常用项目、各类小工具等。如需模板请在【DotNet技术官】回复【Notion模板】即可获取。