. NetCore obtains configuration information in Json and Xml formats, corejson

Source: Internet
Author: User
Tags xml attribute

. NetCore obtains configuration information in Json and Xml formats, corejson

This article will share with you how to obtain Configuration information in Json and Xml formats. It mainly introduces the use of the Configuration extension method, because the netcore web application is already embedded in the appsettings by default in Startup. the configuration information of the json file, so I put the test point on the netcore console application. The configuration file used on the console is also common, and the official website instances mainly explain the json format, the xml format has been directly introduced, so I have shared this article, hoping to help you;

  1. Obtain Json configuration information
  2. Get Xml configuration information
  3. Get xml node attribute values

Can the configuration file not be placed with the application? The answer is yes.

For the netstandard extension of netcore, it comes with the configuration file information operation class, because the core Web application and console application are unified, so the following describes the test case demonstration in the console application, but it can also be used for Web applications;

First, we need to reference the following nuget package in the console application (I will test it here based on 2.0 ):

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

Obtain Json configuration information

In addition to the preceding two references, we also need to reference json Configuration:

 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": "shenniu walking 3", "userPwd": "666666", "GaoDeApi": {"UserName": "shenniu walking 1 ", "userPwd": "111111"}, "BaiDuApi": {"userName": "shenniu walking 2", "userPwd": "222222 "}}}

Then, you only need the following code to obtain the file information:

Var configBasePath = Directory. getCurrentDirectory (); // configBasePath = @ "D: \ D \ TTest"; sbLog. append ($ "configuration file directory: {configBasePath} \ n"); var builder = new ConfigurationBuilder (). setBasePath (configBasePath ). addJsonFile ("deleteworkflow. json "); var config = builder. build (); sbLog. append ($ "MyConfig: UserName node value: {config. getSection ("MyConfig: UserName "). value }");

For those who already have core development experience, the above can be understood directly, but for the sake of perfection, we still need to briefly describe:

After the ConfigurationBuilder instance is completed, you must use the SetBasePath method to set the basic path of the configuration file, and then use the AddJsonFile Extension Method to specify the name of the file to be read. The IConfigurationBuilder interface is returned during these steps, finally, you need to execute the load configuration information using the Build method. This builder is somewhat similar to the start method. Let's take a look:

Obviously, the value of MyConfig: UserName node in the configuration file is obtained. Here, the value of MyConfig: UserName node is obtained through the IConfigurationSection GetSection (string key). The function gets the configuration node and configures the node hierarchy through the ":" link, so here we have key = MyConfig: UserName;

To make the program more intuitive and versatile, We can encapsulate the json file as follows:

/// <Summary> /// read the json configuration file /// </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, note that the AddJsonFile method is referenced by Microsoft. extensions. configuration. json extension; Because IConfiguration not only uses the GetSection function, she can also obtain the node based on this [string key] method. The following is the code for obtaining the node information of AMAP and Baidu map configuration respectively:

Var configJson = GetJsonConfig (); sbLog. append ($ "json configuration-MyConfg node value: \ n"); sbLog. append ($ "autonavi-UserName: {configJson. getSection ("MyConfig: GaoDeApi: UserName "). value} \ n "); sbLog. append ($ "Baidu-userName: {configJson [" MyConfig: BaiDuApi: UserName "]} \ n \ r \ n ");

Note: nodes are case-insensitive and can be obtained using ':' for multi-level nodes;

Get Xml configuration information

Xml configuration files are also common. For extended IConfigurationBuilder, we also have methods like json extension. First, we need to reference the following package:

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

Then get the xml configuration file using almost the same code as json:

/// <Summary> /// read the xml configuration file /// </summary> /// <param name = "configFileName"> </param> // <param name = "basePath"> </param> // <returns> </returns> public static IConfigurationRoot GetXmlConfig (string configFileName = "etettings. 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 IConfigurationBuilder is extended. In this example, public static IConfigurationBuilder AddXmlFile (this IConfigurationBuilder builder, Action <XmlConfigurationSource> configureSource) is used to transmit the configuration file name and basic path;

Next, create and initialize the appsettings. xml configuration file:

<MyConfig> <GaoDeApi> <UserName des = "autonavi account"> 1 </UserName> <userPwd> 111111 </userPwd> </GaoDeApi> <BaiDuApi> <userName des = "Baidu account"> shiniu walking 2 </userName> <userPwd> 222222 </userPwd> </BaiDuApi> </MyConfig>

Let's take a look at some code for calling the get configuration node:

Var configXml = GetXmlConfig (); sbLog. append ($ "xml configuration-MyConfg node value: \ n"); sbLog. append ($ "autonavi-UserName: {configXml. getSection ("GaoDeApi: UserName "). value} \ n "); sbLog. append ($ "Baidu-userName: {configXml [" BaiDuApi: UserName "]} \ n \ r \ n ");

It can be seen that the method for reading configuration nodes in xml and json is the same as that in ":", indicating hierarchical relationships. However, note that xml does not require the outermost layer and nodes. For example, GaoDeApi: UserName, if json is used, the key here should be like this: MyConfig: GaoDeApi: UserName, which is another difference between the two;

Json and xml configuration information is not available;

Get xml node attribute values

Generally, xml configuration file nodes also have attributes. The preceding xml nodes: <UserName des = "autonavi account"> 1 </UserName>, this des = "" is an attribute. How can we get this value? Here we actually use ':' to associate it. The following code gets the des value of the attribute node:

SbLog. append ($ "autonavi-UserName-des: {configXml. getSection ("GaoDeApi: UserName: des "). value} \ n "); sbLog. append ($ "Baidu-userName-des: {configXml [" BaiDuApi: UserName: des "]} \ n \ r \ n ");

The node name of the xml Attribute cannot be name, or the node name cannot be read successfully. If des is changed to name, information cannot be obtained normally;

Can the configuration file not be placed with the application? The answer is yes.

Some may ask the following question: can the configuration file not be put together with the application? The answer is yes. We only need to put Directory. replace GetCurrentDirectory () (obtain the disk directory where the current application is located) with the basic directory where the configuration file is located, as shown in the following figure: configBasePath = @ "D: \ D \ TTest ";

The entire test case code of this instance is as follows:

Using Microsoft. extensions. configuration; using Microsoft. extensions. configuration. json; using Microsoft. extensions. fileProviders; 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 ("deleteworkflow. 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 ($ "autonavi-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 ($ "autonavi-UserName: {configXml. getSection ("GaoDeApi: UserName "). value} \ n "); sbLog. Append ($ "Baidu-userName: {configXml [" BaiDuApi: UserName "]} \ n \ r \ n"); sbLog. append ($ "autonavi-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> /// read the json configuration file /// </summary> /// <param name = "configFileName"> </param> // <param name = "basePath"> </param> /// <Returns> </returns> public static IConfigurationRoot GetJsonConfig (string configFileName = "etettings. json", string basePath = "") {basePath = string. IsNullOrWhiteSpace (basePath )? Directory. getCurrentDirectory (): basePath; var builder = new ConfigurationBuilder (). setBasePath (basePath ). addJsonFile (configFileName); return builder. build ();} /// <summary> /// read the xml configuration file /// </summary> /// <param name = "configFileName"> </param> // <param name = "basePath"> </param> // <returns> </returns> public static IConfigurationRoot GetXmlConfig (string configFileName = "etettings. xml ", s Tring 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

The above is a small series for you to introduce. netCore obtains the configuration information in Json and Xml format and hopes to help you. If you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.