在.netcore webapi 專案中,我們會把配置資訊同意放置在appsettings.json中,透過新建讀取幫助類,更加簡單的讀取配置資訊。
新建公共類庫資料夾Common,新建公共類庫Web.Core.Common
在Web.Core.Common類庫下新建Helper資料夾,新建AppSettings幫助類
.Net Core6.0 WebAPI專案框架搭建四:新建讀取配置檔案幫助類_List
.Net Core6.0 WebAPI專案框架搭建四:新建讀取配置檔案幫助類_json_02
在AppSettings.cs裡面新增以下程式碼:
/// <summary>
/// appsettings.json操作類
/// </summary>
public class AppSettings
{
static IConfiguration Configuration { get; set; }
static string contentPath { get; set; }
public AppSettings(string contentPath)
{
string Path = "appsettings.json";
Configuration = new ConfigurationBuilder()
.SetBasePath(contentPath)
.Add(new JsonConfigurationSource
{
Path = Path,
Optional = false,
ReloadOnChange = true
}).Build();
}
public AppSettings(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
/// 封裝要操作的字元
/// </summary>
/// <param name="sections">節點配置</param>
/// <returns></returns>
public static string app(params string[] sections)
{
try
{
if (sections.Any())
{
return Configuration[string.Join(":", sections)];
}
}
catch (Exception)
{
}
return "";
}
/// <summary>
/// 遞迴獲取配置資訊陣列
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sections"></param>
/// <returns></returns>
public static List<T> app<T>(params string[] sections)
{
List<T> list = new List<T>();
Configuration.Bind(string.Join(":", sections), list);
return list;
}
}
對webapi新增專案引用
在program.cs裡面新增服務
//註冊appsettings讀取類
builder.Services.AddSingleton(new AppSettings(builder.Configuration));
在appsetting.json裡面新增資料庫連線字串
在program.cs裡面測試下AppSettings讀取配置檔案
執行專案顯示配置檔案內容: