在.Net Framework中,一般通過ConfigurationManager.AppSettings["connectionString"];來讀取config file中的配置信息。
.Net Core沒有提供類似的方法,而是通過配置服務,在控制器初始化的時候實現注入,這種方式很好,也很常見,但是很難做到隨時隨處可用,比如在Net Library工程中訪問配置信息。本文通過自定義中間件的方式,來實現隨時隨處可訪問配置信息
編輯appsettings.json文件
編輯配置文件,增加2個節點,供測試用,如代碼所示,我們的目標是獲取ConnectionStrings中的連接數據庫字符串和AppSettings中的配置項
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo;Trusted_Connection=True;MultipleActiveResultSets=true",
"ProductionConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo_Production;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"AppSettings": {
"Item1": "1",
"Item2": "2",
"Item3": "3"
}
"AllowedHosts": "*"
}
創建自定義中間件
- 創建一個獨立的Net Library工程,比如命名爲“MyProject.Common”
- 新建Confighelper類
public class ConfigHelper
{
internal static IConfiguration Configuration { get; set; }
public static string GetConfig(string key)
{
return Configuration[key];
}
public static string GetConnectionConfig(string key)
{
return Configuration.GetConnectionString(key);
}
}
GetConfig:根據Key-Value的方式獲取配置信息
GetConnectionConfig:獲取配置文件中的連接數據庫字符串
- 新建Config中間件
public class ConfigMiddleware
{
private readonly RequestDelegate _next;
public ConfigMiddleware(RequestDelegate next, IConfiguration configuration)
{
_next = next;
ConfigHelper.Configuration = configuration;
}
public async Task Invoke(HttpContext context)
{
await _next.Invoke(context);
}
}
Config中間件使用
- 註冊Config中間件
打開Startup.cs文件,編輯Config方法,加入app.UseMiddleware<ConfigMiddleware>();
- 隨時隨地獲取配置信息
var conn = ConfigHelper.GetConnectionConfig("DefaultConnection");
var item = ConfigHelper.GetConfig("AppSettings:Item1");