. 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 obtainJsonAndXmlFormat configuration information.ConfigurationThe extension method is used because the netcore web application has embedded the configuration information of the appsettings. json file by default in Startup. Therefore, I put the test point in the netcoreConsole ApplicationOn the console, configuration files are also commonly used, and the instances on the official website mainly explain the json format, which is directly included in the xml format. Therefore, I have shared this article, hope to help you;

  • Obtain Json configuration information
  • Get Xml configuration information
  • 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 needConsole ApplicationREFERENCE The following nuget package (I tested it here based on 2.0 ):

Install-Package Microsoft. Extensions. Configuration-Version 2.0.0

Install-Package Microsoft. Extensions. Configuration. Modify actions-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. Here, the value of MyConfig: UserName node is obtained through IConfigurationSection GetSection (string key); the function is used to obtain the configuration node, and the hierarchical relationship between nodes is configured through":"Link, so the 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 used for multi-level nodes.':'Get;

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 IConfigurationBuilder ExtensionAddXmlFileMethod. 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 ");

We can see that the method for reading configuration nodes in xml and json is the same.":"Hierarchical relationship, but note thatXml does not require the outermost layer and nodes, As shown in the following figure:GaoDeApi: UserNameIn json format, the key here should be as follows:MyConfig: GaoDeApi: UserNameHere is another difference between the two types;

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?':'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 be inconsistent with the application?ReleaseTogether? The answer is yes.

Some may ask the following question:Can the configuration file be inconsistent with the application?ReleaseTogether? 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:

1 using Microsoft. extensions. configuration; 2 using Microsoft. extensions. configuration. json; 3 using Microsoft. extensions. fileProviders; 4 using System; 5 using System. diagnostics; 6 using System. IO; 7 using System. text; 8 9 namespace MyService10 {11 class Program12 {13 static void Main (string [] args) 14 {15 16 Encoding. registerProvider (CodePagesEncodingProvider. instance); 17 Console. outputEncoding = Encoding. getEncoding ("GB2312"); 18 19 var sbLog = new StringBuilder (string. empty); 20 var configBasePath = Directory. getCurrentDirectory (); // configBasePath = @ "D: \ D \ TTest"; 21 sbLog. append ($ "configuration file directory: {configBasePath} \ n"); 22 23 var builder = new ConfigurationBuilder (). 24 SetBasePath (configBasePath ). 25 AddJsonFile ("deleteworkflow. json "); 26 var config = builder. build (); 27 sbLog. append ($ "MyConfig: UserName Node value: {config. getSection ("MyConfig: UserName "). value} \ n \ r \ n "); 28 29 var configJson = GetJsonConfig (); 30 sbLog. append ($ "json configuration-MyConfg node value: \ n"); 31 sbLog. append ($ "autonavi-UserName: {configJson. getSection ("MyConfig: GaoDeApi: UserName "). value} \ n "); 32 sbLog. append ($ "Baidu-userName: {configJson [" MyConfig: BaiDuApi: UserName "]} \ n \ r \ n"); 33 34 var configXml = GetXmlConfig (); 35 sbLog. append ($ "xml configuration-MyConfg node value: \ n"); 36 sbL Og. append ($ "autonavi-UserName: {configXml. getSection ("GaoDeApi: UserName "). value} \ n "); 37 sbLog. append ($ "Baidu-userName: {configXml [" BaiDuApi: UserName "]} \ n \ r \ n"); 38 39 sbLog. append ($ "autonavi-UserName-des: {configXml. getSection ("GaoDeApi: UserName: des "). value} \ n "); 40 sbLog. append ($ "Baidu-userName-des: {configXml [" BaiDuApi: UserName: des "]} \ n \ r \ n"); 41 42 Console. writeLine (sbLog); 43 Console. readLine (); 44} 45 46 // <summary> 4 7 // json configuration file read 48 /// </summary> 49 // <param name = "configFileName"> </param> 50 /// <param name = "basePath"> </param> 51 // <returns> </returns> 52 public static IConfigurationRoot GetJsonConfig (53 string configFileName = "etettings. json ", 54 string basePath =" ") 55 {56 basePath = string. isNullOrWhiteSpace (basePath )? Directory. getCurrentDirectory (): basePath; 57 58 var builder = new ConfigurationBuilder (). 59 SetBasePath (basePath ). 60 AddJsonFile (configFileName); 61 return builder. build (); 62} 63 64 // <summary> 65 // read the xml configuration file 66 // </summary> 67 // <param name = "configFileName"> </ param> 68 // <param name = "basePath"> </param> 69 // <returns> </returns> 70 public static IConfigurationRoot GetXmlConfig (71 string confi GFileName = "etettings. xml", 72 string basePath = "") 73 {74 basePath = string. IsNullOrWhiteSpace (basePath )? Directory. getCurrentDirectory (): basePath; 75 76 var builder = new ConfigurationBuilder (). 77 // SetBasePath (basePath ). 78 AddXmlFile (B => 79 {80 B. path = configFileName; 81 B. fileProvider = new PhysicalFileProvider (basePath); 82}); 83 return builder. build (); 84} 85} 86}

 

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.