本篇將和大家分享的是:如何獲取Json和Xml格式的配置信息,主要介紹的是Configuration擴展方法的使用,因為netcore的web應用在Startup中已經默認嵌入appsettings.json文件的配置信息,故而我把測試點放在在了netcore的控制臺應用上;控制臺上使用配置文件也是常用的事情,并且官網實例主要講解的是json格式,對xml格式直接帶過了,因此有了本篇的分享,希望能給你好的幫助;
- 獲取Json配置信息
- 獲取Xml配置信息
- 獲取xml節點屬性值
配置文件能否不和應用放在一起呢? 答案是肯定的
對于netcore的netstandard擴展來說其自帶了配置文件信息操作類,因為core的Web應用和控制臺應用都是統一的,因此下面講解測試用例在控制臺應用演示的,但是也可用于Web應用;
首先,咋們需要在控制臺應用中引用如下nuget包(我這里測試基于2.0):
1
2
|
Install-Package Microsoft.Extensions.Configuration -Version 2.0.0 Install-Package Microsoft.Extensions.Configuration.Abstractions -Version 2.0.0 |
獲取Json配置信息
要獲取json配置我們除了上面兩個引用外,還需要引用:
1
|
Install-Package Microsoft.Extensions.Configuration.Json -Version 2.0.0 |
這是json配置的基礎引用,我們在控制臺應用中創建appsettings.json文件,并定義如下json配置文件信息:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
{ "MyConfig" : { "UserName" : "神牛步行3" , "userPwd" : "666666" , "GaoDeApi" : { "UserName" : "神牛步行1" , "userPwd" : "111111" }, "BaiDuApi" :{ "userName" : "神牛步行2" , "userPwd" : "222222" } } } |
然后只需要如下代碼,即可獲取到該文件信息:
1
2
3
4
5
6
7
|
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的意思;來看看效果圖:
很顯然這里獲取到了配置文件中的MyConfig:UserName節點的值,這里通過 IConfigurationSection GetSection(string key); 函數獲取配置節點,配置節點層級關系通過“:”鏈接,因此這里就有了key=MyConfig:UserName;
為了程序的美觀性和多使用性,這里吧獲取json文件的封裝為如下方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/// <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] 方式獲取節點,下面是分別獲取高德地圖和百度地圖配置節點信息的代碼和效果圖:
1
2
3
4
|
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配置信息
xml配置文件也是我們常見的,對已擴展的IConfigurationBuilder來說,我們同樣也有類似于json那樣擴展的方法,首先需要引用如下包:
1
|
Install-Package Microsoft.Extensions.Configuration.Xml -Version 2.0.0 |
然后幾乎和json同樣的代碼獲取xml配置文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
/// <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配置文件信息:
1
2
3
4
5
6
7
8
9
10
|
<MyConfig> <GaoDeApi> <UserName des= "高德的賬號" >神牛步行1</UserName> <userPwd>111111</userPwd> </GaoDeApi> <BaiDuApi> <userName des= "百度的賬號" >神牛步行2</userName> <userPwd>222222</userPwd> </BaiDuApi> </MyConfig> |
再來看看調用獲取配置節點的部分代碼:
1
2
3
4
|
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節點屬性值
通常xml配置文件節點還有屬性(attribute),如上面的xml節點: <UserName des="高德的賬號">神牛步行1</UserName> ,這個des=""就是屬性,我們要怎么才能獲取這個值呢;這里其實同樣還是通過':'來關聯的,如下代碼獲取屬性節點des的值:
1
2
|
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; using Microsoft.Extensions.FileProviders; using System; using System.Diagnostics; using System.IO; using System.Text; namespace MyService { class Program { static void Main( string [] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Console.OutputEncoding = Encoding.GetEncoding( "GB2312" ); var sbLog = new StringBuilder( string .Empty); 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}\n\r\n" ); 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" ); 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" ); sbLog.Append($ "高德-UserName-des:{configXml.GetSection(" GaoDeApi:UserName:des ").Value}\n" ); sbLog.Append($ "百度-userName-des:{configXml[" BaiDuApi:UserName:des "]}\n\r\n" ); Console.WriteLine(sbLog); Console.ReadLine(); } /// <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(); } /// <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(); } } } |
總結
以上所述是小編給大家介紹的.NetCore獲取Json和Xml格式的配置信息,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/wangrudong003/archive/2017/09/18/7535650.html