. NETCORE gets configuration information in JSON and XML formats

Time:2021-4-25

This article will share with you: how to obtain configuration information in JSON and XML format, mainly introduces the use of configuration extension method, because the web application of NETCORE has been embedded in startup by default appsettings.json File configuration information, so I put the test point on the NETCORE console application; The use of configuration files on the console is also a common thing, and the example of the official website mainly explains the JSON format, and has directly introduced the XML format, so with this sharing, I hope it can help you;

  1. Get JSON configuration information
  2. Get XML configuration information
  3. Get XML node attribute value

Can configuration files not be put with applications? The answer is yes

For the netstandard extension of NETCORE, it comes with configuration file information operation class. Because the web application and console application of core are unified, the test cases are demonstrated in console application, but they can also be used in web application;

First of all, we need to refer to 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

In addition to the above two references, we need to refer to


 Install-Package Microsoft.Extensions.Configuration.Json -Version 2.0.0 

This is the basic reference of JSON configuration, which we create in the console application appsettings.json File, and define the following JSON configuration file information:

{
 "MyConfig": {
 "User name": "Shenniu walk 3,",
 "userPwd": "666666",
 "GaoDeApi": {
  "User name": "Shenniu walk 1,",
  "userPwd": "111111"
 },
 "BaiDuApi":{
  "Username": "Shenniu walk 2,",
  "userPwd": "222222"
 }
 }
}

Then, only the following code is needed to obtain the file information:

var configBasePath = Directory.GetCurrentDirectory(); //configBasePath = @"D:\D\TTest";
sbLog.Append ($"directory of configuration file: {configbasepath} n");
var builder = new ConfigurationBuilder().
     SetBasePath(configBasePath).
     AddJsonFile("appsettings.json");
var config = builder.Build();
sbLog.Append ($"MyC onfig:UserName Value of node:{ config.GetSection ("MyC onfig:UserName ").Value}");

For those who already have experience in core development, the above can be understood directly. However, for the sake of a perfect explanation, here is a brief introduction:

After the instance of configurationbuilder is completed, you need to set the basic path of the configuration file through the setbasepath method, and then specify the name of the file to read through the addjsonfile extension method; All of these steps return iconfigurationbuilder interface. Finally, build method is needed to load configuration information. This builder is a bit similar to start; Let’s take a look at the renderings

It’s obvious that myc in the configuration file is obtained here onfig:UserName The value of the node, here through iconfiguration section getsection (string key); Function to obtain the configuration node, and the hierarchical relationship of the configuration node is linked through the “:” link, so here is key = myc onfig:UserName ;

In order to make the program beautiful and multi-purpose, we can encapsulate the JSON file as follows:

/// <summary>
///JSON configuration file reading
/// </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, notice that the addjsonfile method is referenced through an open section Microsoft.Extensions.Configuration.Json Extended; extended; As iconfiguration not only uses getsection function, it can also obtain nodes according to this [string key]. The following is the code and effect diagram for obtaining the node information of Gaode map and Baidu map respectively:

var configJson = GetJsonConfig();
sbLog.Append ($"JSON configuration - value of myconfg node::");
sbLog.Append ($"Gaode user name:{ configJson.GetSection ("MyC onfig:GaoDeApi :UserName").Value}\n");
sbLog.Append ($"Baidu - Username: {configjson [" myc onfig:BaiDuApi :UserName"]}\n\r\n");

Note: nodes are not case sensitive, and multilevel nodes are obtained by ‘:’;

Get XML configuration information

XML configuration files are also common to us. For the extended iconfiguration builder, we also have a method similar to that of JSON. First, we need to refer to the following package:


 Install-Package Microsoft.Extensions.Configuration.Xml -Version 2.0.0 

Then get the XML configuration file with almost the same code as JSON

/// <summary>
///XML configuration file reading
/// </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 iconfiguration builder is extended. This example uses the public static iconfiguration builder addxmlfile (this iconfiguration builder, action < xmlconfigurationsource > configuresource) to transfer the configuration file name and basic path for diversification;

Next, create and initialize appsettings.xml Profile information:

<MyConfig>
 <GaoDeApi>
 < user name des = "Gaode's account number" > Shenniu walk1 < / user name >
 <userPwd>111111</userPwd>
 </GaoDeApi>
 <BaiDuApi>
 < user name des = "Baidu's account" > Shenniu walk2 < / user name >
 <userPwd>222222</userPwd>
 </BaiDuApi>
</MyConfig>

Let’s look at part of the code that calls to get the configuration node

var configXml = GetXmlConfig();
sbLog.Append ($"XML configuration - value of myconfg node):";
sbLog.Append ($"Gaode user name:{ configXml.GetSection ("GaoDeApi:UserName").Value}\n");
sbLog.Append ($"Baidu - User Name: {configxml [" baiduapi: user name "]} n / R / N");

It can be seen that XML and JSON read configuration nodes in the same way. The “:” represents the hierarchical relationship, but the special point is that XML does not need the outermost layer and node, such as here’s: gaodeapi: username. If you follow the JSON method, the key here should be like this: myc onfig:GaoDeApi : user name, here is another difference between the two; As shown in the figure:

You can get the configuration information of JSON and XML;

Get XML node attribute value

Usually, the XML configuration file node also has attributes, such as the above XML node: < user name des = “Gaode’s account” > Shenniu walk1 < / user name >, and the des = “is an attribute. How can we get this value; In fact, it is also associated by ‘:’ here. The following code gets the value of attribute node des:

sbLog.Append ($"Gaode username des:{ configXml.GetSection ("GaoDeApi:UserN ame:des ").Value}\n");
sbLog.Append ($"Baidu username des: {configxml [" baiduapi: user n ame:des "]}\n\r\n");

XML attribute node name cannot be name, otherwise it cannot be read successfully; If DES is changed to name, you can’t get information normally, so keep in mind;

Can configuration files not be put with applications? The answer is yes

Some friends will ask a question: can configuration files not be put together with applications? The answer is yes, we just need to Directory.GetCurrentDirectory () (get the disk directory where the current application is located) just replace it with the basic directory where the configuration file is located. For example, here I have: configbasepath = @ “D: (d) ttest”;

The following is the whole test case code of 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 ($"directory of configuration file: {configbasepath} n");
   var builder = new ConfigurationBuilder().
    SetBasePath(configBasePath).
    AddJsonFile("appsettings.json");
   var config = builder.Build();
   sbLog.Append ($"MyC onfig:UserName Value of node:{ config.GetSection ("MyC onfig:UserName ").Value}\n\r\n");
   var configJson = GetJsonConfig();
   sbLog.Append ($"JSON configuration - value of myconfg node::");
   sbLog.Append ($"Gaode user name:{ configJson.GetSection ("MyC onfig:GaoDeApi :UserName").Value}\n");
   sbLog.Append ($"Baidu - Username: {configjson [" myc onfig:BaiDuApi :UserName"]}\n\r\n");
   var configXml = GetXmlConfig();
   sbLog.Append ($"XML configuration - value of myconfg node):";
   sbLog.Append ($"Gaode user name:{ configXml.GetSection ("GaoDeApi:UserName").Value}\n");
   sbLog.Append ($"Baidu - User Name: {configxml [" baiduapi: user name "]} n / R / N");
   sbLog.Append ($"Gaode username des:{ configXml.GetSection ("GaoDeApi:UserN ame:des ").Value}\n");
   sbLog.Append ($"Baidu username des: {configxml [" baiduapi: user n ame:des "]}\n\r\n");
   Console.WriteLine(sbLog);
   Console.ReadLine();
  }
  /// <summary>
  ///JSON configuration file reading
  /// </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 reading
  /// </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();
  }
 }
}

summary

NETCORE can get the configuration information of JSON and XML format. I hope it can help you. If you have any questions, please leave me a message and Xiaobian will reply you in time. Thank you very much for your support to developer!