This article will share with you how to get the configuration information in JSON and XML format, the main introduction is the use of the configuration extension method, the. Netcore get the knowledge about the configuration information in JSON and XML format, let's have a look at the friends who are interested.
This article will share with you: How to get the configuration information in JSON and XML format, the main introduction is the use of the configuration extension method, Because the Netcore Web application has already embedded the configuration information of the Appsettings.json file by default in startup, I put the test point on the console application of the Netcore, the use of the configuration file on the console is also a common thing, and the official website instance is mainly about the JSON format, the XML Format directly with, so with this article share, hope can give you help;
-
Get JSON configuration information
-
Get XML configuration information
-
Get XML Node Property value
Can the configuration file not be put together with the app? The answer is yes.
For Netcore's Netstandard extension, it comes with the profile information operation class, because the core Web application and console application are unified, so the following is a demonstration of the test case in the console application, but it can also be used for Web applications;
First, we need to refer to the following NuGet packages in the console app (I test here 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 we need a reference in addition to the above two references:
Install-package Microsoft.extensions.configuration.json-version 2.0.0
This is the underlying reference to the JSON configuration, and we create the Appsettings.json file in the console app and define the following JSON profile information:
{
"MyConfig": {
"UserName": "God Cow Walk 3",
"userPwd": "666666",
"GaoDeApi": {
"UserName": "God Cow Walk 1",
"userPwd": "111111"
},
"BaiDuApi": {
"userName": "God Cow Walk 2",
"userPwd": "222222"
}
}
}
You can then get the file information by just the following code:
var configBasePath = Directory.GetCurrentDirectory (); // configBasePath = @ "D: \ D \ TTest";
sbLog.Append ($ "Configuration file directory: {configBasePath} \ n");
var builder = new ConfigurationBuilder ().
SetBasePath (configBasePath).
AddJsonFile ("appsettings.json");
var config = builder.Build ();
sbLog.Append ($ "MyConfig: UserName node value: {config.GetSection (" MyConfig: UserName "). Value}");
For those who already have the core development experience, the above can be read directly, but in order to improve the explanation here still need to simply say:
After the Configurationbuilder instance, you need to set the configuration file base path through the Setbasepath method, and then specify the read file name through the Addjsonfile extension method These steps are returned by the Iconfigurationbuilder interface, and finally the build method executes the load configuration information, which is somewhat similar to the meaning of start; take a look:
It is clear that the value of the Myconfig:username node in the configuration file is obtained here through the Iconfigurationsection GetSection (string key); The function obtains the configuration node, configures the node hierarchy relationship through the ":" Link, so here is the key=myconfig:username;
For the aesthetic and multi-usability of the program, here's how to get the JSON file encapsulated as follows:
/// <summary>
/// json configuration file read
/// </ 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 ();
}
Here, note that the Addjsonfile method is extended by the Microsoft.Extensions.Configuration.Json referenced by the open section; Since iconfiguration not only uses getsection functions, she can also This[string key] way to get the node, the following is the code to get the map and Baidu Map configuration node information separately:
var configJson = GetJsonConfig ();
sbLog.Append ($ "json configuration-MyConfg node value: \ n");
sbLog.Append ($ "高 德 -UserName: {configJson.GetSection (" MyConfig: GaoDeApi: UserName "). Value} \ n");
sbLog.Append ($ "Baidu-userName: {configJson [" MyConfig: BaiDuApi: UserName "]} \ n \ r \ n");
Note: Nodes are not case sensitive, multilevel nodes use ': ' to get;
Get XML configuration information
XML configuration files are also common to us, and for extended iconfigurationbuilder, we also have methods that are similar to JSON, and we first need to refer to the following packages:
Install-package Microsoft.extensions.configuration.xml-version 2.0.0
And then almost the same code as JSON gets the XML configuration file:
/// <summary>
/// xml configuration file read
/// </ 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 the Addxmlfile method of extending Iconfigurationbuilder, this example uses the public static Iconfigurationbuilder Addxmlfile for diversification (this Iconfigurationbuilder Builder, action<xmlconfigurationsource> Configuresource) to pass the configuration file name and the underlying path;
Below to create and initialize the Appsettings.xml profile information:
<MyConfig>
<GaoDeApi>
<UserName des = "Gold's account"> God walking 1 </ UserName>
<userPwd> 111111 </ userPwd>
</ GaoDeApi>
<BaiDuApi>
<userName des = "Baidu's account"> God walking 2 </ userName>
<userPwd> 222222 </ userPwd>
</ BaiDuApi>
</ MyConfig>
Take a look at the part of the code that invokes the Get configuration node:
var configXml = GetXmlConfig ();
sbLog.Append ($ "xml configuration-MyConfg node value: \ n");
sbLog.Append ($ "高 德 -UserName: {configXml.GetSection (" GaoDeApi: UserName "). Value} \ n");
sbLog.Append ($ "Baidu-userName: {configXml [" BaiDuApi: UserName "]} \ n \ r \ n");
You can see that the XML and JSON read the configuration node the same way ":" represents a hierarchical relationship, but the special note is that XML does not require the outermost and node, as here: Gaodeapi:username, if JSON, the key should be this: myconfig : Gaodeapi:username, here is another difference between the two kinds;
JSON and XML configuration information can be obtained;
Get XML Node Property value
Typically the XML configuration file node also has attributes (attribute), such as the XML node above: <username des= "Gold account" > 1</username>, this des= "" is the attribute, How are we going to get this value? In fact, it is also associated with ': ', the following code gets the value of the attribute node des:
sbLog.Append ($ "高 德 -UserName-des: {configXml.GetSection (" GaoDeApi: UserName: des "). Value} \ n");
sbLog.Append ($ "Baidu-userName-des: {configXml [" BaiDuApi: UserName: des "]} \ n \ r \ n");
The XML attribute node name cannot be named, otherwise it cannot be read successfully; If DES is changed to name here, it will not be able to get the information normally, remember in heart;
Can the configuration file not be put together with the app? The answer is yes.
Some friends will ask a question: Can the configuration file not be put together with the application? The answer is yes, we just have to replace the directory.getcurrentdirectory () (Get the disk directory where the current application resides) to the base directory where the configuration file is located, as I have here: Configbasepath = @ "D:\D\TTest";
The following is the entire test case code for this instance:
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 ($ "Configuration file directory: {configBasePath} \ n");
var builder = new ConfigurationBuilder ().
SetBasePath (configBasePath).
AddJsonFile ("appsettings.json");
var config = builder.Build ();
sbLog.Append ($ "MyConfig: UserName node value: {config.GetSection (" MyConfig: UserName "). Value} \ n \ r \ n");
var configJson = GetJsonConfig ();
sbLog.Append ($ "json configuration-MyConfg node value: \ n");
sbLog.Append ($ "高 德 -UserName: {configJson.GetSection (" MyConfig: GaoDeApi: UserName "). Value} \ n");
sbLog.Append ($ "Baidu-userName: {configJson [" MyConfig: BaiDuApi: UserName "]} \ n \ r \ n");
var configXml = GetXmlConfig ();
sbLog.Append ($ "xml configuration-MyConfg node value: \ n");
sbLog.Append ($ "高 德 -UserName: {configXml.GetSection (" GaoDeApi: UserName "). Value} \ n");
sbLog.Append ($ "Baidu-userName: {configXml [" BaiDuApi: UserName "]} \ n \ r \ n");
sbLog.Append ($ "高 德 -UserName-des: {configXml.GetSection (" GaoDeApi: UserName: des "). Value} \ n");
sbLog.Append ($ "Baidu-userName-des: {configXml [" BaiDuApi: UserName: des "]} \ n \ r \ n");
Console.WriteLine (sbLog);
Console.ReadLine ();
}
/// <summary>
/// json configuration file read
/// </ 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 configuration file read
/// </ 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 ();
}
}
}