前言:什么是集成配置系統(tǒng)?
集成配置系統(tǒng)的主要目的是將應用程序的配置信息與代碼分離,使得配置信息可以在不需要修改代碼的情況下進行更改。這樣可以提高應用程序的靈活性和可維護性。
ASP.NET Core 提供了一種靈活的配置系統(tǒng),可以輕松地將配置信息從不同的來源加載到應用程序中,并且可以根據環(huán)境變量、命令行參數、JSON 文件、XML 文件、環(huán)境變量等不同來源來管理配置。
本文主要講解如何在 Asp.net core webapi 中應用集成配置系統(tǒng)
Step By Step 步驟
-
創(chuàng)建一個 ASP.NET Core webapi 項目
-
在 SQL Server 數據庫中手動創(chuàng)建表 T_Configs,用于保存配置信息
- 表包含Id、Name、Value這3列
- Id列定義為整數類型的標識列
- Name列和Value列都定義為字符串類型
- Name列為配置項的名字
- Value列為配置項的值
-
在T_Configs表中增加兩行數據
1 Redis {"ConnStr":"127.0.0.1:16379,allowadmin=true"} 2 Smtp {"Host":"smtp.example.com", "UserName":"test", "Password":"mypass123"}
-
安裝并啟動 Redis
- 可下載 Redis 便攜包,下載后在命令行窗口啟動即可
- 下載地址:https://redis.io/download/
-
引用以下 Nuget 包:
StackExchange.Redis
System.Data.SqlClient
Zack.AnyDBConfigProvider -
在項目中創(chuàng)建一個SmtpOptions實體類,對應Smtp的配置值
public record SmtpOptions { public string Host { get; set; } public string UserName { get; set; } public string Password { get; set; } }
-
在項目上右擊,選擇【管理用戶機密】,生成 Secrets.json
-
可以看到在 .csproj 文件中生成了 UserSecretsId 節(jié)點
<UserSecretsId>29c6a656-872a-40dc-9793-2a9add90e9fe</UserSecretsId>
-
Secrets.json 存儲在:
C:\Users\Jacky\AppData\Roaming\Microsoft\UserSecrets\29c6a656-872a-40dc-9793-2a9add90e9fe\secrets.json
-
編寫 Secrets.json 內容為:
{ "ConnectionStrings": { "configServer": "Server=(localdb)\\mssqllocaldb;Database=TestDB;Trusted_Connection=True;MultipleActiveResultSets=true" } }
-
關閉 Secrets.json 文件后,右鍵重新【管理用戶機密】可以再次打開 Secrets.json 文件
-
-
打開 Program.cs,編寫代碼進行配置系統(tǒng)的初始化(注意,看代碼注釋)
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();
-
在控制器中通過構造方法注入獲取SmtpOptions和Redis連接對象文章來源:http://www.zghlxwxcb.cn/news/detail-789288.html
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using StackExchange.Redis; namespace 配置系統(tǒng)集成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}"; } } }
擴展
為了簡化開發(fā),在ASP.NET Core項目中,WebApplication類的CreateBuilder方法會按照下面的順序來提供默認的配置:文章來源地址http://www.zghlxwxcb.cn/news/detail-789288.html
- 加載現(xiàn)有的IConfiguration。
- 加載項目根目錄下的appsettings.json
- 加載項目根目錄下的appsettings.Environment.json,其中Environment代表當前運行環(huán)境的名字
- 當程序運行在開發(fā)環(huán)境下,程序會加載“用戶機密”配置
- 加載環(huán)境變量中的配置
- 加載命令行中的配置
到了這里,關于使用 Asp.net core webapi 集成配置系統(tǒng),提高程序的靈活和可維護性的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!