企业网站建设与实施调查报告,wordpress 文章引用,不会写代码怎样做网站,红河网站建设前言#xff1a;什么是集成配置系统#xff1f;
集成配置系统的主要目的是将应用程序的配置信息与代码分离#xff0c;使得配置信息可以在不需要修改代码的情况下进行更改。这样可以提高应用程序的灵活性和可维护性。
ASP.NET Core 提供了一种灵活的配置系统#xff0c;可…
前言什么是集成配置系统
集成配置系统的主要目的是将应用程序的配置信息与代码分离使得配置信息可以在不需要修改代码的情况下进行更改。这样可以提高应用程序的灵活性和可维护性。
ASP.NET Core 提供了一种灵活的配置系统可以轻松地将配置信息从不同的来源加载到应用程序中并且可以根据环境变量、命令行参数、JSON 文件、XML 文件、环境变量等不同来源来管理配置。
本文主要讲解如何在 Asp.net core webapi 中应用集成配置系统
Step By Step 步骤 创建一个 ASP.NET Core webapi 项目 在 SQL Server 数据库中手动创建表 T_Configs用于保存配置信息 表包含Id、Name、Value这3列Id列定义为整数类型的标识列Name列和Value列都定义为字符串类型Name列为配置项的名字Value列为配置项的值 在T_Configs表中增加两行数据 1 Redis {ConnStr:127.0.0.1:16379,allowadmintrue}
2 Smtp {Host:smtp.example.com, UserName:test, Password:mypass123}安装并启动 Redis 可下载 Redis 便携包下载后在命令行窗口启动即可下载地址https://redis.io/download/ 引用以下 Nuget 包 StackExchange.Redis System.Data.SqlClient Zack.AnyDBConfigProvider 在项目中创建一个SmtpOptions实体类对应Smtp的配置值 public record SmtpOptions
{public string Host { get; set; }public string UserName { get; set; }public string Password { get; set; }
}在项目上右击选择【管理用户机密】生成 Secrets.json 可以看到在 .csproj 文件中生成了 UserSecretsId 节点 UserSecretsId29c6a656-872a-40dc-9793-2a9add90e9fe/UserSecretsIdSecrets.json 存储在 C:\Users\Jacky\AppData\Roaming\Microsoft\UserSecrets\29c6a656-872a-40dc-9793-2a9add90e9fe\secrets.json编写 Secrets.json 内容为 {ConnectionStrings: { configServer: Server(localdb)\\mssqllocaldb;DatabaseTestDB;Trusted_ConnectionTrue;MultipleActiveResultSetstrue }
}关闭 Secrets.json 文件后右键重新【管理用户机密】可以再次打开 Secrets.json 文件 打开 Program.cs编写代码进行配置系统的初始化注意看代码注释 using StackExchange.Redis;
using System.Data.SqlClient;var builder WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();// 1.读取用户机密文件中的sqlserver连接串
builder.Host.ConfigureAppConfiguration((_, configBuilder) {string connStr builder.Configuration.GetConnectionString(configServer);configBuilder.AddDbConfiguration(() new SqlConnection(connStr));
});// 2.采用直接读取builder.Configuration的方式来读取数据库中的配置并注册服务
builder.Services.ConfigureSmtpOptions(builder.Configuration.GetSection(Smtp));
builder.Services.AddSingletonIConnectionMultiplexer(sp {string connStr builder.Configuration.GetValuestring(Redis:ConnStr);return ConnectionMultiplexer.Connect(connStr);
}); var app builder.Build();// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{app.UseSwagger();app.UseSwaggerUI();
}app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();在控制器中通过构造方法注入获取SmtpOptions和Redis连接对象 using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using StackExchange.Redis;namespace 配置系统集成1.Controllers
{[ApiController][Route([controller]/[action])]public class HomeController : ControllerBase{private readonly IOptionsSnapshotSmtpOptions smtpOptions;private readonly IConnectionMultiplexer connMultiplexer;// 通过构造方法注入获取SmtpOptions和Redis连接对象public HomeController(IOptionsSnapshotSmtpOptions smtpOptions,IConnectionMultiplexer connMultiplexer){this.smtpOptions smtpOptions;this.connMultiplexer connMultiplexer;}// 读取配置信息连接 Redis 读取数据[HttpGet]public async Taskstring Index(){var opt smtpOptions.Value;var timeSpan connMultiplexer.GetDatabase().Ping();//写入和读取 Key-valuevar database connMultiplexer.GetDatabase(1);await database.StringSetAsync(name, Jacky);string str await database.StringGetAsync(name);return $Smtp:{opt} timeSpan:{timeSpan} str:{str};}}
}扩展
为了简化开发在ASP.NET Core项目中WebApplication类的CreateBuilder方法会按照下面的顺序来提供默认的配置
加载现有的IConfiguration。加载项目根目录下的appsettings.json加载项目根目录下的appsettings.Environment.json其中Environment代表当前运行环境的名字当程序运行在开发环境下程序会加载“用户机密”配置加载环境变量中的配置加载命令行中的配置