.net core來勢已不可阻擋。既然擋不了,那咱們就順應它。瞭解它並學習它。今天咱們就來看看和以前.net版本的配置文件讀取方式有何異同,這裏不在贅述.NET Core 基礎知識。json
ps:更新版,更新了多種方式實現讀取配置文件信息,各位看官結合本身實際狀況選擇合適的讀取方式便可。api
咱們先來看下初始的Json文件是怎樣的:app
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "Test": { "One": 123, "Two": "456", "Three": "789", "Content": { "cone": 111, "ctwo": "瀟十一郎" } } }
讀取Json配置文件信息,咱們須要安裝Microsoft.Extensions.Configuration.Json
包,以下:
ide
而後再 調用AddJsonFile把Json配置的Provider添加到ConfigurationBuilder中,實現以下:函數
咱們將Configuration 屬性改爲學習
public static IConfiguration Configuration { get; set; }ui
而後再ConfigureServices 中將Json配置的Provider添加到ConfigurationBuilder中url
var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); services.AddSingleton<IConfiguration>(Configuration);//配置IConfiguration的依賴
而後配置完,咱們就能夠讀取了,固然,若是是在其餘地方調用,就須要經過構造函數注入IConfiguration spa
讀取方式一:使用key讀取,以下:.net
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); } }
最後 ,咱們來跑一下演示效果以下:
事務老是不斷髮展,有更優的作法,那就必定要摒棄之前不太美的實現,如今補充一種實現獲取配置文件的方法,更爲優雅美觀:
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"; }
在具體的控制器或者類中注入:
private readonly IConfiguration _config; public SmsServices(IConfiguration config) { _config = config; }
var templateId = _config[ConfigurationKeys.SMS_VERIFY_CODE_TEMPLATE];
完!