本篇将和大家分享的是:如何擷取Json和Xml格式的配置資訊,主要介紹的是Configuration擴充方法的使用,因為netcore的web應用在Startup中已經預設嵌入appsettings.json檔案的配置資訊,故而我把測試點放在在了netcore的控制台應用上;控制台上使用配置檔案也是常用的事情,并且官網執行個體主要講解的是json格式,對xml格式直接帶過了,是以有了本篇的分享,希望能給你好的幫助;
- 擷取Json配置資訊
- 擷取Xml配置資訊
- 擷取xml節點屬性值
- 配置檔案能否不和應用放在一起呢? 答案是肯定的
對于netcore的netstandard擴充來說其自帶了配置檔案資訊操作類,因為core的Web應用和控制台應用都是統一的,是以下面講解測試用例在控制台應用示範的,但是也可用于Web應用;
首先,咋們需要在控制台應用中引用如下nuget包(我這裡測試基于2.0):
Install-Package Microsoft.Extensions.Configuration -Version 2.0.0
Install-Package Microsoft.Extensions.Configuration.Abstractions -Version 2.0.0
要擷取json配置我們除了上面兩個引用外,還需要引用:
Install-Package Microsoft.Extensions.Configuration.Json -Version 2.0.0
這是json配置的基礎引用,我們在控制台應用中建立appsettings.json檔案,并定義如下json配置檔案資訊:
{
"MyConfig": {
"UserName": "神牛步行3",
"userPwd": "666666",
"GaoDeApi": {
"UserName": "神牛步行1",
"userPwd": "111111"
},
"BaiDuApi":{
"userName": "神牛步行2",
"userPwd": "222222"
}
}
}
然後隻需要如下代碼,即可擷取到該檔案資訊:
var configBasePath = Directory.GetCurrentDirectory(); //configBasePath = @"D:\D\TTest";
sbLog.Append($"配置檔案所在目錄:{configBasePath}\n");
var builder = new ConfigurationBuilder().
SetBasePath(configBasePath).
AddJsonFile("appsettings.json");
var config = builder.Build();
sbLog.Append($"MyConfig:UserName節點的值:{config.GetSection("MyConfig:UserName").Value}");
對于已經有core開發經驗的朋友而言,上面直接能看懂,不過為了完善的講解這裡還是需要簡單說下的:
ConfigurationBuilder執行個體過後需要通過SetBasePath方法設定配置檔案基礎路徑,再通過AddJsonFile擴充方法指定讀取的檔案名稱;這些步驟執行傳回的都是IConfigurationBuilder接口,最後還需要Build方法執行加載配置資訊,這個builder有點類似于start的意思;來看看效果圖:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuIDM4EzNzQGOwE2MwYWN5YmZxIjNkV2N1gTYzYWNzY2YfdWbp9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.png)
很顯然這裡擷取到了配置檔案中的MyConfig:UserName節點的值,這裡通過 IConfigurationSection GetSection(string key); 函數擷取配置節點,配置節點層級關系通過“:”連結,是以這裡就有了key=MyConfig:UserName;
為了程式的美觀性和多使用性,這裡吧擷取json檔案的封裝為如下方法:
/// <summary>
/// json配置檔案讀取
/// </summary>
/// <param name="configFileName"></param>
/// <param name="basePath"></param>
/// <returns></returns>
public static IConfigurationRoot GetJsonConfig(
string configFileName = "appsettings.json",
string basePath = "")
{
basePath = string.IsNullOrWhiteSpace(basePath) ? Directory.GetCurrentDirectory() : basePath;
var builder = new ConfigurationBuilder().
SetBasePath(basePath).
AddJsonFile(configFileName);
return builder.Build();
}
對了這裡注意下AddJsonFile方法是通過開節引用的 Microsoft.Extensions.Configuration.Json 擴充的;由于IConfiguration不光用GetSection函數,她也能根據 this[string key] 方式擷取節點,下面是分别擷取高德地圖和百度地圖配置節點資訊的代碼和效果圖:
var configJson = GetJsonConfig();
sbLog.Append($"json配置-MyConfg節點的值:\n");
sbLog.Append($"高德-UserName:{configJson.GetSection("MyConfig:GaoDeApi:UserName").Value}\n");
sbLog.Append($"百度-userName:{configJson["MyConfig:BaiDuApi:UserName"]}\n\r\n");
注意:節點不區分大小寫,多級節點使用‘:’擷取;
xml配置檔案也是我們常見的,對已擴充的IConfigurationBuilder來說,我們同樣也有類似于json那樣擴充的方法,首先需要引用如下包:
Install-Package Microsoft.Extensions.Configuration.Xml -Version 2.0.0
然後幾乎和json同樣的代碼擷取xml配置檔案:
/// <summary>
/// xml配置檔案讀取
/// </summary>
/// <param name="configFileName"></param>
/// <param name="basePath"></param>
/// <returns></returns>
public static IConfigurationRoot GetXmlConfig(
string configFileName = "appsettings.xml",
string basePath = "")
{
basePath = string.IsNullOrWhiteSpace(basePath) ? Directory.GetCurrentDirectory() : basePath;
var builder = new ConfigurationBuilder().
//SetBasePath(basePath).
AddXmlFile(b =>
{
b.Path = configFileName;
b.FileProvider = new PhysicalFileProvider(basePath);
});
return builder.Build();
}
差別在于擴充IConfigurationBuilder的AddXmlFile方法,本次示例為了多樣化使用了 public static IConfigurationBuilder AddXmlFile(this IConfigurationBuilder builder, Action<XmlConfigurationSource> configureSource) 來傳遞配置檔案名稱和基礎路徑;
下面來建立并初始化appsettings.xml配置檔案資訊:
<MyConfig>
<GaoDeApi>
<UserName des="高德的賬号">神牛步行1</UserName>
<userPwd>111111</userPwd>
</GaoDeApi>
<BaiDuApi>
<userName des="百度的賬号">神牛步行2</userName>
<userPwd>222222</userPwd>
</BaiDuApi>
</MyConfig>
再來看看調用擷取配置節點的部分代碼:
var configXml = GetXmlConfig();
sbLog.Append($"xml配置-MyConfg節點的值:\n");
sbLog.Append($"高德-UserName:{configXml.GetSection("GaoDeApi:UserName").Value}\n");
sbLog.Append($"百度-userName:{configXml["BaiDuApi:UserName"]}\n\r\n");
能夠看出xml和json讀取配置節點的方式一樣“:”表示層級關系,但是特别注意點在于xml不需要最外層跟節點,如這裡的:GaoDeApi:UserName,如果按照json方式的話這裡的key應該是這樣:MyConfig:GaoDeApi:UserName,這裡就是兩種的另外一種差別;如圖:
不出以外json和xml配置資訊都能擷取到了;
通常xml配置檔案節點還有屬性(attribute),如上面的xml節點: <UserName des="高德的賬号">神牛步行1</UserName> ,這個des=""就是屬性,我們要怎麼才能擷取這個值呢;這裡其實同樣還是通過':'來關聯的,如下代碼擷取屬性節點des的值:
sbLog.Append($"高德-UserName-des:{configXml.GetSection("GaoDeApi:UserName:des").Value}\n");
sbLog.Append($"百度-userName-des:{configXml["BaiDuApi:UserName:des"]}\n\r\n");
xml屬性節點名稱不能是name,不然是無法讀取成功的;如這裡的des改成name名稱的話,無法正常擷取資訊,謹記于心;
配置檔案能否不和應用放在一起呢? 答案是肯定的
有部分朋友會提出一個問題:配置檔案能否不和應用放在一起呢? 答案是肯定的,我們隻需把Directory.GetCurrentDirectory()(擷取目前應用所在磁盤目錄)替換成配置檔案所在的基礎目錄就行了,如我這裡的: configBasePath = @"D:\D\TTest";
下面是本次執行個體的整個測試用例代碼:
1 using Microsoft.Extensions.Configuration;
2 using Microsoft.Extensions.Configuration.Json;
3 using Microsoft.Extensions.FileProviders;
4 using System;
5 using System.Diagnostics;
6 using System.IO;
7 using System.Text;
8
9 namespace MyService
10 {
11 class Program
12 {
13 static void Main(string[] args)
14 {
15
16 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
17 Console.OutputEncoding = Encoding.GetEncoding("GB2312");
18
19 var sbLog = new StringBuilder(string.Empty);
20 var configBasePath = Directory.GetCurrentDirectory(); //configBasePath = @"D:\D\TTest";
21 sbLog.Append($"配置檔案所在目錄:{configBasePath}\n");
22
23 var builder = new ConfigurationBuilder().
24 SetBasePath(configBasePath).
25 AddJsonFile("appsettings.json");
26 var config = builder.Build();
27 sbLog.Append($"MyConfig:UserName節點的值:{config.GetSection("MyConfig:UserName").Value}\n\r\n");
28
29 var configJson = GetJsonConfig();
30 sbLog.Append($"json配置-MyConfg節點的值:\n");
31 sbLog.Append($"高德-UserName:{configJson.GetSection("MyConfig:GaoDeApi:UserName").Value}\n");
32 sbLog.Append($"百度-userName:{configJson["MyConfig:BaiDuApi:UserName"]}\n\r\n");
33
34 var configXml = GetXmlConfig();
35 sbLog.Append($"xml配置-MyConfg節點的值:\n");
36 sbLog.Append($"高德-UserName:{configXml.GetSection("GaoDeApi:UserName").Value}\n");
37 sbLog.Append($"百度-userName:{configXml["BaiDuApi:UserName"]}\n\r\n");
38
39 sbLog.Append($"高德-UserName-des:{configXml.GetSection("GaoDeApi:UserName:des").Value}\n");
40 sbLog.Append($"百度-userName-des:{configXml["BaiDuApi:UserName:des"]}\n\r\n");
41
42 Console.WriteLine(sbLog);
43 Console.ReadLine();
44 }
45
46 /// <summary>
47 /// json配置檔案讀取
48 /// </summary>
49 /// <param name="configFileName"></param>
50 /// <param name="basePath"></param>
51 /// <returns></returns>
52 public static IConfigurationRoot GetJsonConfig(
53 string configFileName = "appsettings.json",
54 string basePath = "")
55 {
56 basePath = string.IsNullOrWhiteSpace(basePath) ? Directory.GetCurrentDirectory() : basePath;
57
58 var builder = new ConfigurationBuilder().
59 SetBasePath(basePath).
60 AddJsonFile(configFileName);
61 return builder.Build();
62 }
63
64 /// <summary>
65 /// xml配置檔案讀取
66 /// </summary>
67 /// <param name="configFileName"></param>
68 /// <param name="basePath"></param>
69 /// <returns></returns>
70 public static IConfigurationRoot GetXmlConfig(
71 string configFileName = "appsettings.xml",
72 string basePath = "")
73 {
74 basePath = string.IsNullOrWhiteSpace(basePath) ? Directory.GetCurrentDirectory() : basePath;
75
76 var builder = new ConfigurationBuilder().
77 //SetBasePath(basePath).
78 AddXmlFile(b =>
79 {
80 b.Path = configFileName;
81 b.FileProvider = new PhysicalFileProvider(basePath);
82 });
83 return builder.Build();
84 }
85 }
86 }
git位址:
https://github.com/shenniubuxing3nuget釋出包:
https://www.nuget.org/profiles/shenniubuxing3