asp.net core 系列 11 配置configuration (下)
四. 檔案配置提供程式AddIniFile、 AddXmlFile、AddJsonFile
FileConfigurationProvider 是從檔案系統載入配置的基類。 以下配置提供程式專用於特定檔案型別:
(1) INI 配置提供程式 IniConfigurationProvider: FileConfigurationProvider
(2) JSON 配置提供程式 JsonConfigurationProvider: FileConfigurationProvider
(3) XML 配置提供程式 XmlConfigurationProvider: FileConfigurationProvider
4.1 INI 配置提供程式
IniConfigurationProvider 在執行時從 INI 檔案鍵值對載入配置,若要啟用 INI 檔案配置,請在 ConfigurationBuilder 的例項上呼叫 AddIniFile 擴充套件方法。冒號可用作 INI 檔案配置中的節分隔符。下面是一個ini配置檔案通用示例:
[section0] key0=value key1=value [section1] subsection:key=value [section2:subsection0] key=value [section2:subsection1] key=value
//下面是獲取各節點中的value值,需要載入的鍵。 section0:key0 section0:key1 section1:subsection:key section2:subsection0:key section2:subsection1:key
下面示例是使用config.AddIniFile方法載入一個config.ini檔案,該方法過載允許指定:(1) optional檔案是否可選,(2)reloadOnChange如果檔案更改,是否過載配置。IFileProvider只讀該檔案。
config.SetBasePath(Directory.GetCurrentDirectory()); config.AddIniFile("config.ini", optional: true, reloadOnChange: true);
//OtherPages/Page1頁面訪問,val 值value string val=Configuration.GetSection("section0").GetSection("key0").Value;
4.2 JSON 配置提供程式
JsonConfigurationProvider 在執行時期間從 JSON 檔案鍵值對載入配置。若要啟用 JSON 檔案配置,請在 ConfigurationBuilder 的例項上呼叫 AddJsonFile 擴充套件方法。下面是使用config. AddJsonFile方法載入一個config.json檔案,具體格式可參考appsettings.json
config.SetBasePath(Directory.GetCurrentDirectory()); config.AddJsonFile("config.json", optional: true, reloadOnChange: true);
效果就不再具體演示,重點講下注意事項: 使用 CreateDefaultBuilder 初始化新的 WebHostBuilder 時,會自動呼叫 AddJsonFile 兩次。 呼叫該方法來從以下檔案載入配置:(1)appsettings.json – 首先讀取此檔案。(2) appsettings.{Environment}.json。也就是說呼叫二次AddJsonFile後,AddJsonFile才會呼叫上面顯示指定的config.json.
4.3 XML 配置提供程式
XmlConfigurationProvider 在執行時從 XML 檔案鍵值對載入配置。若要啟用 XML 檔案配置,請在 ConfigurationBuilder 的例項上呼叫 AddXmlFile 擴充套件方法。XML檔案建立配置鍵值對時,將忽略配置檔案的根節點。 不要在檔案中指定文件型別定義 (DTD) 或名稱空間。
config.SetBasePath(Directory.GetCurrentDirectory()); config.AddXmlFile("config.xml", optional: true, reloadOnChange: true);
(1)下面是一個xml配置檔案通用示例:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <section0> <key0>value</key0> <key1>value</key1> </section0> <section1> <key0>value</key0> <key1>value</key1> </section1> </configuration> //下面是獲取各節點中的value值,需要載入的鍵。 section0:key0 section0:key1 section1:key0 section1:key1
(2) 如果使用 name 屬性來區分元素,則使用相同元素名稱的重複元素可以正常工作:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <section name="section0"> <key name="key0">value</key> <key name="key1">value</key> </section> <section name="section1"> <key name="key0">value</key> <key name="key1">value</key> </section> </configuration> //下面是獲取各節點中的value值,需要載入的鍵。 section:section0:key:key0 section:section0:key:key1 section:section1:key:key0 section:section1:key:key1
(3) 屬性可用於提供值
<?xml version="1.0" encoding="UTF-8"?> <configuration> <key attribute="value" /> <section> <key attribute="value" /> </section> </configuration> //下面是獲取各屬性中的value值,需要載入的鍵。 key:attribute section:key:attribute
五. Key-per-file 配置提供程式 AddKeyPerFile
KeyPerFileConfigurationProvider 使用目錄的檔案作為配置鍵值對。 該鍵是檔名。 該值包含檔案的內容。 Key-per-file 配置提供程式用於 Docker 託管方案。若要啟用 Key-per-file 配置,請在 ConfigurationBuilder 的例項上呼叫 AddKeyPerFile 擴充套件方法。 檔案的 directoryPath 必須是絕對路徑。
下面示例是使用config.AddKeyPerFile方法載入一個目錄檔案,在使用Docker 託管時具體參考官方文件。
config.SetBasePath(Directory.GetCurrentDirectory()); var path = Path.Combine(Directory.GetCurrentDirectory(), "path/to/files"); config.AddKeyPerFile(directoryPath: path, optional: true);
六. 記憶體配置提供程式AddInMemoryCollection
MemoryConfigurationProvider 使用記憶體中集合作為配置鍵值對。若要啟用記憶體中集合配置,請在 ConfigurationBuilder 的例項上呼叫 AddInMemoryCollection 擴充套件方法。
/// <summary> /// 構建記憶體物件的鍵值對 /// </summary> public static readonly Dictionary<string, string> _dict = new Dictionary<string, string> { {"MemoryCollectionKey1", "value1"}, {"MemoryCollectionKey2", "value2"} }; public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.AddInMemoryCollection(_dict); }) .UseStartup<Startup>();
//OtherPages/Page1頁面訪問,val 值value string val=Configuration.GetSection("MemoryCollectionKey1").Value
七. 讀取GetValue、GetSection、GetChildren 和 Exists
7.1 GetValue
ConfigurationBinder.GetValue<T> 從具有指定鍵的配置中提取一個值,並將其轉換為指定型別。 如果未找到該鍵,則過載允許你提供預設值。以下示例使用鍵 NumberKey 從配置中提取字串值,鍵入該值作為 int,並將值儲存在變數 intValue 中。 如果在配置鍵中找不到 NumberKey,則 intValue 會接收 99 的預設值。
var intValue = config.GetValue<int>("NumberKey", 99);
7.2 GetSection
IConfiguration.GetSection 使用指定的子節鍵提取配置子節。GetSection 永遠不會返回 null。 如果找不到匹配的節,則返回空 IConfigurationSection。
{ "section0": { "key0": "value", "key1": "value" }, "section1": { "key0": "value", "key1": "value" }, "section2": { "subsection0" : { "key0": "value", "key1": "value" }, "subsection1" : { "key0": "value", "key1": "value" } } }
//返回僅包含 section1 中鍵值對的 IConfigurationSection 物件 var configSection = _config.GetSection("section1"); //獲取 section2:subsection0 中鍵的值 var configSection = _config.GetSection("section2:subsection0");
7.3 GetChildren
//在上面的json結構中,獲取section2下面的子節點 var configSection = _config.GetSection("section2"); var children = configSection.GetChildren();
7.4 Exists
//在上面的json結構中,確定配置節是否存在, 為false,是因為配置資料中沒有 section2:subsection2 節點 var sectionExists = _config.GetSection("section2:subsection2").Exists();
八. 繫結到類
使用GetSection方法呼叫 Bind 可以構造 POCO 物件。POCO就是簡單CLR物件(Plain Old CLR Object),這種類不繼承於任何物件(或者說直接繼承於Object),示例應用包含 Starship 模型 (Models/Starship.cs)。
config.SetBasePath(Directory.GetCurrentDirectory()); config.AddJsonFile("starship.json",false,true);
Starship實體對應JSON的 starship
節點
{ "starship": { "name": "USS Enterprise", "registry": "NCC-1701", "class": "Constitution", "length": 304.8, "commissioned": false }, "trademark": "Paramount Pictures Corp. http://www.paramount.com" }
// OtherPages/Page1頁面繫結starship 節點到Starship實體中 var starship = new Models.Starship(); Configuration.GetSection("starship").Bind(starship);
總結:
Configuration配置的其它知識點如:將陣列繫結至類、自定義配置提供程式、在啟動期間訪問配置、在 Razor Pages 頁或 MVC 檢視中訪問配置等等, 請參考官方文件。
在Configuration配置的上下二篇中,講到了Configuration對不同配置來源的載入和讀取方法,Microsoft.Extensions.Configuration.IConfiguration中全是以Get開頭的只讀方法,並沒有涉及到對配置來源(如json或xml檔案)的增刪改操作。像配置的xml檔案,是否需要引入System.Xml.Linq來操作xml檔案的增刪改操呢?帶著這個疑問在以後章節再瞭解。
參考文獻
官方資料: ofollow,noindex">asp.net core 配置