.NET Core讀取配置文件方式詳細(xì)總結(jié)
基于.NET Core的跨平臺(tái)開(kāi)發(fā),配置文件與之前.NET Framework采用xml的config文件不同,目前主要是采用json文件鍵值對(duì)配置方式讀取。
參考網(wǎng)上相關(guān)資料總結(jié)如下:
一. 引入擴(kuò)展 System.Configuration.ConfigurationManager
Nuget 下載擴(kuò)展,Install-Package System.Configuration.ConfigurationManager
使用方式:添加配置文件App.config。讀取方式與原.NET Framework方式一致
優(yōu)點(diǎn):兼容.NET Framework 原有配置方式
缺點(diǎn):項(xiàng)目運(yùn)行過(guò)程中若需修改App.config文件,對(duì)項(xiàng)目中輸出的內(nèi)容沒(méi)有絲毫影響,Debug發(fā)現(xiàn)獲取到的值的確沒(méi)有變化,需要重新編譯才生效。
二. 引入擴(kuò)展 Microsoft.Extensions.Options.ConfigurationExtensions
Nuget 下載擴(kuò)展,
Install-Package Microsoft.Extensions.Options.ConfigurationExtensions
Install-Package Microsoft.Extensions.Configuration.FileExtensions
Install-Package Microsoft.Extensions.Configuration.Json
使用方式:參考微軟官網(wǎng)
優(yōu)點(diǎn):可以讀取application.json中的配置參數(shù),不再使用XML可以說(shuō)很好的貼近Core的設(shè)計(jì)理念
缺點(diǎn):運(yùn)行時(shí)修改json文件讀取到的內(nèi)容不會(huì)改變,但是至少重啟項(xiàng)目可以修改,若要運(yùn)行時(shí)候修改json文件監(jiān)聽(tīng)實(shí)現(xiàn)監(jiān)聽(tīng)變化。查看源碼,可以發(fā)現(xiàn) 雖然配置信息是通過(guò)AddSingleton注入的
但同時(shí)也注入了IOptionsChangeTokenSource ,故只需要在獲取配置信息時(shí)將IOptions<> 替換為 IOptionsMonitor<>(通過(guò)監(jiān)聽(tīng)的Option來(lái)獲取信息),并通過(guò) IOptionsMonitor<>.CurrentValue獲取即可實(shí)時(shí)獲取到最新的配置信息(存在修改監(jiān)聽(tīng))
另外就是,這個(gè)方法采用的是反序列化的原理,也就是必須有一個(gè)跟配置文件對(duì)應(yīng)的實(shí)體類(lèi)才可以,這個(gè)感覺(jué)比較雞肋,放棄。
三. 自定義擴(kuò)展方法,這個(gè)實(shí)現(xiàn)自己寫(xiě),原理是監(jiān)聽(tīng)文件是否變更,來(lái)刷新Configuration 配置實(shí)現(xiàn)。
參考園友一個(gè)實(shí)現(xiàn),具體需要是否有效,要花時(shí)間實(shí)踐一下,原鏈接地址,代碼如下:
復(fù)制代碼
public class ConfigurationManager { /// <summary> /// 配置內(nèi)容 /// </summary> private static NameValueCollection _configurationCollection = new NameValueCollection(); /// <summary> /// 配置監(jiān)聽(tīng)響應(yīng)鏈堆棧 /// </summary> private static Stack<KeyValuePair<string, FileSystemWatcher>> FileListeners = new Stack<KeyValuePair<string, FileSystemWatcher>>(); /// <summary> /// 默認(rèn)路徑 /// </summary> private static string _defaultPath = Directory.GetCurrentDirectory() + "\\appsettings.json"; /// <summary> /// 最終配置文件路徑 /// </summary> private static string _configPath = null; /// <summary> /// 配置節(jié)點(diǎn)關(guān)鍵字 /// </summary> private static string _configSection = "AppSettings"; /// <summary> /// 配置外連接的后綴 /// </summary> private static string _configUrlPostfix = "Url"; /// <summary> /// 最終修改時(shí)間戳 /// </summary> private static long _timeStamp = 0L; /// <summary> /// 配置外鏈關(guān)鍵詞,例如:AppSettings.Url /// </summary> private static string _configUrlSection { get { return _configSection + "." + _configUrlPostfix; } } static ConfigurationManager() { ConfigFinder(_defaultPath); } /// <summary> /// 確定配置文件路徑 /// </summary> private static void ConfigFinder(string Path) { _configPath = Path; JObject config_json = new JObject(); while (config_json != null) { config_json = null; FileInfo config_info = new FileInfo(_configPath); if (!config_info.Exists) break; FileListeners.Push(CreateListener(config_info)); config_json = LoadJsonFile(_configPath); if (config_json[_configUrlSection] != null) _configPath = config_json[_configUrlSection].ToString(); else break; } if (config_json == null || config_json[_configSection] == null) return; LoadConfiguration(); } /// <summary> /// 讀取配置文件內(nèi)容 /// </summary> private static void LoadConfiguration() { FileInfo config = new FileInfo(_configPath); var configColltion = new NameValueCollection(); JObject config_object = LoadJsonFile(_configPath); if (config_object == null || !(config_object is JObject)) return; if (config_object[_configSection]!=null) { foreach (JProperty prop in config_object[_configSection]) { configColltion[prop.Name] = prop.Value.ToString(); } } _configurationCollection = configColltion; } /// <summary> /// 解析Json文件 /// </summary> /// <param name="FilePath">文件路徑</param> /// <returns></returns> private static JObject LoadJsonFile(string FilePath) { JObject config_object = null; try { StreamReader sr = new StreamReader(FilePath, Encoding.Default); config_object = JObject.Parse(sr.ReadToEnd()); sr.Close(); } catch { } return config_object; } /// <summary> /// 添加監(jiān)聽(tīng)樹(shù)節(jié)點(diǎn) /// </summary> /// <param name="info"></param> /// <returns></returns> private static KeyValuePair<string, FileSystemWatcher> CreateListener(FileInfo info) { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.BeginInit(); watcher.Path = info.DirectoryName; watcher.Filter = info.Name; watcher.IncludeSubdirectories = false; watcher.EnableRaisingEvents = true; watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size; watcher.Changed += new FileSystemEventHandler(ConfigChangeListener); watcher.EndInit(); return new KeyValuePair<string, FileSystemWatcher>(info.FullName, watcher); } private static void ConfigChangeListener(object sender, FileSystemEventArgs e) { long time = TimeStamp(); lock (FileListeners) { if (time > _timeStamp) { _timeStamp = time; if (e.FullPath != _configPath || e.FullPath == _defaultPath) { while (FileListeners.Count > 0) { var listener = FileListeners.Pop(); listener.Value.Dispose(); if (listener.Key == e.FullPath) break; } ConfigFinder(e.FullPath); } else { LoadConfiguration(); } } } } private static long TimeStamp() { return (long)((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds * 100); } private static string c_configSection = null; public static string ConfigSection { get { return _configSection; } set { c_configSection = value; } } private static string c_configUrlPostfix = null; public static string ConfigUrlPostfix { get { return _configUrlPostfix; } set { c_configUrlPostfix = value; } } private static string c_defaultPath = null; public static string DefaultPath { get { return _defaultPath; } set { c_defaultPath = value; } } public static NameValueCollection AppSettings { get { return _configurationCollection; } } /// <summary> /// 手動(dòng)刷新配置,修改配置后,請(qǐng)手動(dòng)調(diào)用此方法,以便更新配置參數(shù) /// </summary> public static void RefreshConfiguration() { lock (FileListeners) { //修改配置 if (c_configSection != null) { _configSection = c_configSection; c_configSection = null; } if (c_configUrlPostfix != null) { _configUrlPostfix = c_configUrlPostfix; c_configUrlPostfix = null; } if (c_defaultPath != null) { _defaultPath = c_defaultPath; c_defaultPath = null; } //釋放掉全部監(jiān)聽(tīng)響應(yīng)鏈 while (FileListeners.Count > 0) FileListeners.Pop().Value.Dispose(); ConfigFinder(_defaultPath); } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ASP.NET Core 2.2中的Endpoint路由詳解
這篇文章主要介紹了ASP.NET Core 2.2中的Endpoint路由詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-03-03Json返回時(shí)間的格式中出現(xiàn)亂碼問(wèn)題的兩種解決方案
使用Json返回?cái)?shù)據(jù)的時(shí)候時(shí)間的格式一般都會(huì)變了,變成我們不認(rèn)識(shí)的一些字符,那么當(dāng)我們遇到這些問(wèn)題的時(shí)候我們?cè)撛趺唇鉀Q呢,今天我就來(lái)小說(shuō)一下這個(gè)的解決方法2013-10-10Windows Server 2012 R2 Standard搭建ASP.NET Core環(huán)境圖文教程
這篇文章主要介紹了Windows Server 2012 R2 Standard搭建ASP.NET Core環(huán)境圖文教程,需要的朋友可以參考下2016-07-07.NET?中?Channel?類(lèi)簡(jiǎn)單使用方法
Channel?類(lèi)是?.NET?CORE?3.0?后新加入的類(lèi),為我們提供了便利的生產(chǎn)者/消費(fèi)者模式實(shí)現(xiàn)方案,相當(dāng)于是一個(gè)進(jìn)程內(nèi)的內(nèi)存隊(duì)列,而且它沒(méi)有持久化,純內(nèi)存操作,性能是非常非常高的,這篇文章主要介紹了.NET?中?Channel?類(lèi)簡(jiǎn)單使用,需要的朋友可以參考下2024-05-05增加asp.net應(yīng)用程序性能的20種方法(簡(jiǎn)單有效)
增加asp.net應(yīng)用程序性能的20種方法小結(jié),需要的朋友可以參考下,對(duì)于服務(wù)器也需要一些設(shè)置。2010-01-01ASP.NET Core應(yīng)用錯(cuò)誤處理之StatusCodePagesMiddleware中間件針對(duì)響應(yīng)碼呈現(xiàn)錯(cuò)誤頁(yè)面
這篇文章主要給大家介紹了關(guān)于ASP.NET Core應(yīng)用錯(cuò)誤處理之StatusCodePagesMiddleware中間件針對(duì)響應(yīng)碼呈現(xiàn)錯(cuò)誤頁(yè)面的相關(guān)資料,需要的朋友可以參考下2019-01-01Asp.Net MVC 分頁(yè)、檢索、排序整體實(shí)現(xiàn)代碼
很多時(shí)候需要這樣的功能,對(duì)表格進(jìn)行分頁(yè)、排序和檢索。本篇文章主要介紹了Asp.Net MVC 分頁(yè)、檢索、排序整體實(shí)現(xiàn),有興趣的可以了解一下。2017-01-01ASP.NET中GridView 重復(fù)表格列合并的實(shí)現(xiàn)方法
本文通過(guò)GridView 和 Repeater 解決有關(guān)表格顯示數(shù)據(jù)重復(fù)的數(shù)據(jù)列和并的方法,非常實(shí)用,感興趣的朋友一起看下吧2016-08-08.netcore 寫(xiě)快遞100的快遞物流信息查詢(xún)接口的實(shí)現(xiàn)
這篇文章主要介紹了.netcore 寫(xiě)快遞100的快遞物流信息查詢(xún)接口,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04