This article will share with you how to obtain configuration information in Json and Let’s take a look
What I will share with you in this article is: how to obtain configuration information in Json and The configuration information of the appsettings.json file, so I put the test point on the console application of netcore; using configuration files on the console is also a common thing, and the official website examples mainly explain the json format, and directly bring the xml format Passed, so I share this article, I hope it can help you;
Get Json configuration information
Get Xml configuration Information
Get xml node attribute value
Can the configuration file not be placed together with the application? The answer is yes
For netcore's netstandard extension, it comes with a configuration file information operation class. Because core's web application and console application are unified, the test cases are explained below in the console application. Demonstration, but can also be used for web applications;
First, we need to reference the following nuget package in the console application (my test here is based on 2.0):
Install-Package Microsoft.Extensions.Configuration -Version 2.0.0 Install-Package Microsoft.Extensions.Configuration.Abstractions -Version 2.0.0
Get Json configuration information
To get the json configuration, in addition to the above two references, we also need to quote:
Install-Package Microsoft.Extensions.Configuration.Json -Version 2.0.0
This is the basic reference of json configuration. We create the appsettings.json file in the console application and define the following json configuration file information:
{ "MyConfig": { "UserName": "神牛步行3", "userPwd": "666666", "GaoDeApi": { "UserName": "神牛步行1", "userPwd": "111111" }, "BaiDuApi":{ "userName": "神牛步行2", "userPwd": "222222" } } }
Then we only need the following Code, you can get the file information:
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}");
For friends who already have core development experience, the above can be understood directly, but for the sake of complete explanation, here is What needs to be briefly mentioned:
After the ConfigurationBuilder instance, you need to set the base path of the configuration file through the SetBasePath method, and then specify the file name to be read through the AddJsonFile extension method; these steps return the IConfigurationBuilder interface, and finally you need The Build method executes loading configuration information. This builder is somewhat similar to start; let’s take a look at the rendering:
It is obvious that the MyConfig:UserName node in the configuration file is obtained here. The value of the configuration node is obtained here through the IConfigurationSection GetSection(string key); function. The hierarchical relationship of the configuration node is linked through ":", so here is key=MyConfig:UserName;
For the beauty and beauty of the program For more usability, here is the method to encapsulate the json file as follows:
/// <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(); }
By the way, please note that the AddJsonFile method is referenced through the opening section of Microsoft.Extensions.Configuration. Json extended; since IConfiguration not only uses the GetSection function, she can also obtain nodes according to this [string key] method. The following are the codes and renderings for obtaining the configuration node information of Amap and Baidu Map respectively:
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");
Note: Nodes are not case-sensitive, use ':' to obtain multi-level nodes;
Get Xml configuration Information
xml configuration files are also common to us. For the extended IConfigurationBuilder, we also have an extension method similar to json. First, we need to reference the following package:
Install-Package Microsoft.Extensions.Configuration.Xml -Version 2.0.0
Then almost the same code as json to get the xml configuration file:
/// <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(); }
The difference is that the AddXmlFile method of extending IConfigurationBuilder, this time The example uses public static IConfigurationBuilder AddXmlFile(this IConfigurationBuilder builder, Action
The following is to create and initialize the appsettings.xml configuration file information:
<MyConfig> <GaoDeApi> <UserName des="高德的账号">神牛步行1</UserName> <userPwd>111111</userPwd> </GaoDeApi> <BaiDuApi> <userName des="百度的账号">神牛步行2</userName> <userPwd>222222</userPwd> </BaiDuApi> </MyConfig>
Let’s take a look at part of the code that calls the configuration node:
##
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");
Get xml node attribute value
通常xml配置文件节点还有属性(attribute),如上面的xml节点:
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";
下面是本次实例的整个测试用例代码:
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(); } } }
The above is the detailed content of An explanation of how .NetCore obtains configuration information in Json and Xml formats. For more information, please follow other related articles on the PHP Chinese website!