前言
.net core來勢已不可阻擋。既然擋不了,那我們就順應它。了解它並學習它。今天我們就來看看和之前.net版本的配置文件讀取方式有何異同,這里不在贅述.NET Core 基礎知識。
ps:更新版,更新了多種方式實現讀取配置文件信息,各位看官結合自己實際情況選擇合適的讀取方式即可。
實現方式一
我們先來看下初始的Json文件是怎樣的:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"Test": {
"One": 123,
"Two": "456",
"Three": "789",
"Content": {
"cone": 111,
"ctwo": "瀟十一郎"
}
}
}
讀取Json配置文件信息,我們需要安裝Microsoft.Extensions.Configuration.Json 包,如下:
然后再 調用AddJsonFile把Json配置的Provider添加到ConfigurationBuilder中,實現如下:
我們將Configuration 屬性改成
public static IConfiguration Configuration { get; set; }
然后再ConfigureServices 中將Json配置的Provider添加到ConfigurationBuilder中
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
services.AddSingleton<IConfiguration>(Configuration);//配置IConfiguration的依賴
然后配置完,我們就可以讀取了,當然,如果是在其他地方調用,就需要通過構造函數注入IConfiguration
讀取方式一:使用key讀取,如下:
private readonly IConfiguration _configuration;
//構造注入
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
//方式一 通過 Key值獲取
var one = _configuration["Test:One"]; //123
var conw = _configuration["Test:Content:ctwo"]; //瀟十一郎
}
讀取方式二:使用GetValue<T>,需要安裝Microsoft.Extensions.Configuration.Binder包,讀取如下:
private readonly IConfiguration _configuration;
//構造注入
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
//方式二 通過GetValue<T>(string key)方式獲取 第一個是直接獲取key 第二個若查找不到則指定默認值
var two = _configuration.GetValue<int>("Test:One"); //123
var three = _configuration.GetValue<string>("Test:Three"); //789
var ctwo = _configuration.GetValue<string>("Test:Content:ctwo"); //瀟十一郎
var four = _configuration.GetValue<string>("Test:four", "我是默認值"); //我是默認值
}
特別說明一下:GetValue的泛型形式有兩個重載,一個是GetValue("key"),另一個是可以指定默認值的GetValue("key",defaultValue).如果key的配置不存在,第一種結果為default(T),第二種結果為指定的默認值.
上述兩個讀取方式調試圖如下:
實現方式二
注:需要NuGet引入:Microsoft.Extensions.Options.ConfigurationExtensions
①我們再配置文件appsettings.json中 新增自定義API Json如下:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"API": {
"Url": "http://localhost:8080/",
"getclub": "api/club"
}
}
②然后我們定義一個靜態類,再類中申明一個IConfigurationSection 類型變量
private static IConfigurationSection _appSection = null;
③寫一個AppSetting靜態方法獲取到配置的Value項,代碼如下:
public static string AppSetting(string key)
{
string str = string.Empty;
if (_appSection.GetSection(key) != null)
{
str = _appSection.GetSection(key).Value;
}
return str;
}
④需要設置IConfigurationSection初始值,如下:
public static void SetAppSetting(IConfigurationSection section)
{
_appSection = section;
}
⑤然后寫一個根據不同Json項讀取出對應的值即可:
public static string GetSite(string apiName)
{
return AppSetting(apiName);
}
⑥有了以上幾個步驟,基本上讀取代碼已經全部寫完,剩下最后一個最重要的步驟,將要讀取的Json文件配置到Startup.cs的Configure方法中,如下:
這樣,我們就可以很輕松的獲取到我們想要的配置項了,整段CS代碼如下:
/// <summary>
/// 配置信息讀取模型
/// </summary>
public static class SiteConfig
{
private static IConfigurationSection _appSection = null;
/// <summary>
/// API域名地址
/// </summary>
public static string AppSetting(string key)
{
string str = string.Empty;
if (_appSection.GetSection(key) != null)
{
str = _appSection.GetSection(key).Value;
}
return str;
}
public static void SetAppSetting(IConfigurationSection section)
{
_appSection = section;
}
public static string GetSite(string apiName)
{
return AppSetting(apiName);
}
}
最后 ,我們來跑一下演示效果如下:
1|0 補充
事務總是不斷發展,有更優的做法,那就一定要摒棄以前不太美的實現,現在補充一種實現獲取配置文件的方法,更為優雅美觀:
NuGet引入:Microsoft.Extensions.Configuration 包
在appsetting中加入短信相關配置信息:
在Startup.cs中重寫:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
新建一個靜態類:ConfigurationKeys
public class ConfigurationKeys
{
public static string SMS_APP_URL = "sms:url";
public static string SMS_APP_ID = "sms:appid";
public static string SMS_APP_SECRET = "sms:secret";
public static string SMS_VERIFY_CODE_TEMPLATE = "sms:verifycodetemplate";
}
1|1使用
在具體的控制器或者類中注入:
private readonly IConfiguration _config;
public SmsServices(IConfiguration config)
{
_config = config;
}
var templateId = _config[ConfigurationKeys.SMS_VERIFY_CODE_TEMPLATE];
完!





