使用 Asp.net core webapi 集成配置系统,提高程序的灵活和可维护性

  • 使用 Asp.net core webapi 集成配置系统,提高程序的灵活和可维护性已关闭评论
  • 35 次浏览
  • A+
所属分类:.NET技术
摘要

集成配置系统的主要目的是将应用程序的配置信息与代码分离,使得配置信息可以在不需要修改代码的情况下进行更改。这样可以提高应用程序的灵活性和可维护性。

使用 Asp.net core webapi 集成配置系统,提高程序的灵活和可维护性

前言:什么是集成配置系统?

集成配置系统的主要目的是将应用程序的配置信息与代码分离,使得配置信息可以在不需要修改代码的情况下进行更改。这样可以提高应用程序的灵活性和可维护性。

ASP.NET Core 提供了一种灵活的配置系统,可以轻松地将配置信息从不同的来源加载到应用程序中,并且可以根据环境变量、命令行参数、JSON 文件、XML 文件、环境变量等不同来源来管理配置。

本文主要讲解如何在 Asp.net core webapi 中应用集成配置系统

Step By Step 步骤

  1. 创建一个 ASP.NET Core webapi 项目

  2. 在 SQL Server 数据库中手动创建表 T_Configs,用于保存配置信息

    • 表包含Id、Name、Value这3列
    • Id列定义为整数类型的标识列
    • Name列和Value列都定义为字符串类型
    • Name列为配置项的名字
    • Value列为配置项的值
  3. 在T_Configs表中增加两行数据

    1	Redis	{"ConnStr":"127.0.0.1:16379,allowadmin=true"} 2	Smtp	{"Host":"smtp.example.com", "UserName":"test", "Password":"mypass123"} 
  4. 安装并启动 Redis

  5. 引用以下 Nuget 包:

    StackExchange.Redis
    System.Data.SqlClient
    Zack.AnyDBConfigProvider

  6. 在项目中创建一个SmtpOptions实体类,对应Smtp的配置值

    public record SmtpOptions { 	public string Host { get; set; } 	public string UserName { get; set; } 	public string Password { get; set; } } 
  7. 在项目上右击,选择【管理用户机密】,生成 Secrets.json

    • 可以看到在 .csproj 文件中生成了 UserSecretsId 节点

      <UserSecretsId>29c6a656-872a-40dc-9793-2a9add90e9fe</UserSecretsId> 
    • Secrets.json 存储在:

      C:UsersJackyAppDataRoamingMicrosoftUserSecrets29c6a656-872a-40dc-9793-2a9add90e9fesecrets.json 
    • 编写 Secrets.json 内容为:

      {   "ConnectionStrings": { "configServer": "Server=(localdb)\mssqllocaldb;Database=TestDB;Trusted_Connection=True;MultipleActiveResultSets=true" } } 
    • 关闭 Secrets.json 文件后,右键重新【管理用户机密】可以再次打开 Secrets.json 文件

  8. 打开 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.Configure<SmtpOptions>(builder.Configuration.GetSection("Smtp")); builder.Services.AddSingleton<IConnectionMultiplexer>(sp => { 	string connStr = builder.Configuration.GetValue<string>("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(); 
  9. 在控制器中通过构造方法注入获取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 IOptionsSnapshot<SmtpOptions> smtpOptions; 		private readonly IConnectionMultiplexer connMultiplexer;  		// 通过构造方法注入获取SmtpOptions和Redis连接对象 		public HomeController( 			IOptionsSnapshot<SmtpOptions> smtpOptions, 			IConnectionMultiplexer connMultiplexer) 		{ 			this.smtpOptions = smtpOptions; 			this.connMultiplexer = connMultiplexer; 		}  		// 读取配置信息,连接 Redis 读取数据 		[HttpGet] 		public async Task<string> Index() 		{ 			var opt = smtpOptions.Value; 			var timeSpan = connMultiplexer.GetDatabase().Ping(); 			 			//写入和读取 Key-value 			var 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方法会按照下面的顺序来提供默认的配置:

  1. 加载现有的IConfiguration。
  2. 加载项目根目录下的appsettings.json
  3. 加载项目根目录下的appsettings.Environment.json,其中Environment代表当前运行环境的名字
  4. 当程序运行在开发环境下,程序会加载“用户机密”配置
  5. 加载环境变量中的配置
  6. 加载命令行中的配置