Interpretation of ASP.net 5 & MVC6 Series (5): Configuration configuration Information Management _ self-study process

Source: Internet
Author: User
Tags json key string static class


In the previous section, we know that the new MVC program abandoned the original Web.config file mechanism, take instead of the Config.json, today we will delve into the content of the configuration file.



Basic usage



The new configuration information mechanism is rewritten under the Microsoft.Framework.ConfigurationModel namespace, overwriting not only the XML format, but also JSON, INI, environment variables, and so on. In the constructor of the startup class in the template sample program, there are the following statements:


Setup configuration sources.
Configuration = new Configuration ()
 . Addjsonfile ("Config.json")
 . Addenvironmentvariables ();


The purpose of this statement is to add the Config.json file and the environment variable information to the configuration information container for reading. While reading, it can be read in the form of a collection index or a Get method, as shown in the following example:


var path = configuration["path"];
var path = configuration.get ("path");


Among them, multiple-level key reading, need to be separated by a colon between multiple levels of names, examples are as follows:


var connstring = configuration.get ("Data:DefaultConnection:ConnectionString");


As you can see from the preceding paragraphs, the configuration example is not a global instance, so if you want to read this information somewhere else, you need to save the instance on a global static variable.



Architecture Design



The new configuration information processing mechanism, after rewriting, is more lightweight, and is cross-platform, and can be obtained from multiple data sources without having to adhere to the. config file and even set different configuration information for different environments (development, testing, production). The key entities of the entire configuration mechanism are shown in the following figure:






Let's one by one tell you about the specific role of these classes:



1.IConfiguration-an instance interface for configuration information, on which,,, andindexerGetTryGetSetOtherReloadmethods such as this are used to get configuration information based on Key/value.



2.IConfigurationSource-This interface unifies the interface methods used by each configuration source, such asTryGet,Setand the most important method of reading configuration informationload, to load the information into the configuration subsystem.



3.IConfigurationSourceContainer-a container for all configuration source information that allows you to load configuration information for various configuration sources on a separate configuration instance. This interface has only oneAddmethod for addingIConfigurationSourcethe configuration source information that is based on.



4.Configuration-This class implementsIConfigurationinterfaces andIConfigurationSourceContainerinterfaces, and does not save all types of configuration information based on Key/value.



5.ConfigurationExtensions-Extended method for fast loading of configuration information, such asAddCommandLine, andAddIniFileso on.



Under the Microsoft.Framework.ConfigurationModel namespace, there are currently 6 different types of configuration source types that can be used, respectively, as follows:



1.MemoryConfigurationSource-the configuration source does not currently have a built-in Add/load extension method (for exampleAddMemoryConfiguration), but you can load a collection of key/value types for this purpose (such asIEnumerable<KeyValuePair<string, string>>type).



2.IniFileConfigurationSource-This configuration source allows you to load the INI file configuration information based on the Key/value format into the configuration system.



3.CommandLineConfigurationSource-load command line parameter information from the start of the program into the configuration system.



4.EnvironmentVariablesConfigurationSource-Load the environment variable information of the operating system into the configuration system, in Azure website, environment variables can be set through the Web interface, which is very convenient to manage.



5.JsonConfigurationSource-Load the JSON file's information into the configuration system.



6.XmlconfigurationSource-Load the information from the XML file into the configuration system.



Detailed usage



First, because the configuration system is a multiple-instance type, you first declare an example before each use, with the following code:


IConfiguration configuration = new configuration ();


Add Memoryconfigurationsource



Because there is no extension method for Memoryconfigurationsource to quickly load configuration information on Iconfigurationsourcecontainer, if you want to load this type of configuration information, you need to add it as follows:


((Iconfigurationsourcecontainer) Configuration)
 . ADD (New Memoryconfigurationsource (New
  list<keyvaluepair<string, string>> {
  new KeyValuePair <string, string> ("Mem-key1", "mem-value1"),
  new keyvaluepair<string, string> ("Mem-key2", " Mem-value2 "))
  );
Value Way
var someConfiguration1 = configuration["Mem-key1"];
var someConfiguration2 = configuration.get ("Mem-key2");


Add Inifileconfigurationsource



The configuration information for the Inifileconfigurationsource type can be loaded by extension methods as follows:


var configuration = new configuration (). Addinifile ("Path\\to\\your\\configuration-ini-file.ini");


The format template for the INI file is as follows:


[Ini-sec]
Ini-key1=value-a
ini-key2=value-b
[ini-sec2]
ini-key1=value-c
ini-key2=value-d


[Ini-sec] Here is a custom configuration section name that can be configured with multiple Key/value items under each configuration section. In the same way as in the basic example, the hierarchy (in this case, between the configuration section and the key) is separated by a colon, as shown in the following example:


var someConfiguration1 = configuration["Ini-sec:ini-key1"];
var someConfiguration2 = configuration.get ("Ini-sec2:ini-key2");


Add Commandlineconfigurationsource



The parameters that are passed in when the program uses the K run naming process can be read through the configuration source, or you canAddCommandLineadd them manually by extension methods, as follows:


var configuration = new configuration (). Addcommandline (new string[] {"Key1=value1", "Key2=value2", "@key3 =value3"});


Each string in the above example is Key/value format, and you can use less special symbols such as $,/, and so on. For these key values, you can also useswitchMappingsclasses with parameter constructorsCommandLineConfigurationSourceto map some keys,switchMappingsand the data types and examples of the parameters are as follows:


var mappings = new dictionary<string, string> (stringcomparer.ordinalignorecase)
{
 {"Key1", "Tom1"},
 {"Key2", "Tom2"},
};


Since there is currently no extension method for the Commandlineconfigurationsource class, we still need to instantiate the class ourselves and add it to the Configuration container as follows:


((Iconfigurationsourcecontainer) Configuration). ADD (New Commandlineconfigurationsource (Commandlinearguments, switchmappings:mappings));





After executing the above code, the values for the following two keys are the same when the configuration value is obtained:


var value1 = configuration.get ("Key1");
var value2 = configuration["Tom1"]; Tom1 the value of this key is actually key1, because TOM1 is the key1 mapping





In the mapping, the new mapping key string can not include "/" characters, otherwise it will be reported that the same key can not be passed in two times, otherwise it will also report abnormal load configuration information, if there is duplicate key, then the value of the last key will overwrite the value of the previous key. When loading commandline configuration information, if a key string is prefixed with-, then a new key must be mapped to the old key using switchmapping, otherwise there will be an error.



Add Environmentvariablesconfigurationsource



ironmentVariablesConfigurationSourceYou can add the operating system's environment variables to the configuration system, and you can customize these environment variables, such as when VS development debugging, you can add some key/value to the following interface:






The value method is as follows:


var someConfiguration1 = configuration["Env_var_key1"];
var someConfiguration2 = configuration["Env_var_key2"];


In addition, the configuration source also supports Azure environment variables and connection strings, so you can also set MSSQL, MYSQL, and custom link strings in the Azure interface, but these link strings need to start with the following string:



1.MySQL =>MYSQLCONNSTR_



2.MS SQL =>SQLCONNSTR_



3.SQL Azure DB =>SQLAZURECONNSTR_



4.Custom DB =>CUSTOMCONNSTR_



For example, the key/value defining a development environment is as follows:


Key => sqlconnstr_devlocal
Value => server=localhost;database=test_db; Trusted_connection=true;


After you load the information in the form of addenvironmentvariables (), we can access this information in the following ways:


var connstring = configuration["Data:devlocal:ConnectionString"];


That is, in Azure, the key to the environment variable is converted to data: A custom identifier: A format such as ConnectionString. If your key is not a custom key (toCUSTOMCONNSTR_begin with), you can get the provider name of the connection string in the following way, as shown in the following example:


var providername = configuration["Data:devlocal:ProviderName"];
return: System.Data.SqlClient


EnvironmentVariablesConfigurationSourceA prefix filtering method is also provided to load part of the information, such as:


((Iconfigurationsourcecontainer) Configuration). ADD (New Environmentvariablesconfigurationsource ("Data:"));


In this way, when the information is obtained, the data in the key value can be omitted and the example is as follows:


var conn1 = configuration["devlocal:connectionstring"];
var conn2 = configuration["Devlocal:providername"];


Add Jsonconfigurationsource



At the beginning of the article, we saw that the JSON configuration file was loaded, and the file was loaded with an.AddJsonFile("test.json")extension method, but don't forget, To first refer to the Microsoft.Framework.ConfigurationModel.Json assembly in the Project.json dependencies.



For example, if your Config.json file contains the following:


{"
 Data": {"defaultconnection": {"
 ConnectionString": "
  server= (localdb) \\mssqllocaldb;database= Aspnet5-webapplication1-64357659-de50-4b1e-b005-30310e7ee1ef; Trusted_connection=true; Multipleactiveresultsets=true "
 }
 },
 " EntityFramework ": {"
 Applicationdbcontext ": {
  " ConnectionString ":" Data:DefaultConnection:ConnectionString "}}}


You can access the link string using the following methods:


var conn = configuration["Data:DefaultConnection:ConnectionString"];


Add Xmlconfigurationsource



XmlconfigurationSourceConfiguration sources and Jsonconfigurationsource configuration sources are similar, first referencing the MICROSOFT.FRAMEWORK.CONFIGURATIONMODEL.XML assembly, and then calling.AddXmlFile("test.xml").



If your profile test.xml the contents of the following:


<root>
 <key1>Jsinh</key1>
 <key2 subkey2= "Hello World"/>
</root>


Gets the form, there is a slight difference (ignores root node root):


var S1 = configuration["Key1"]; return Jsinh
var s2 = configuration["Key2:subkey2"];//Back to Hello World


Note, however, that the common key cannot be repeated, and that the following files will be error-prone when they are read.


<root>
 <key1>Jsinh</key1>
 <key2 subkey2= "Hello World"/>
 <key2 subkey2= " Hello world Again "/>
</root>


Sensitive information configuration (new features of RC edition)



After the release of the RC, Microsoft added a new sensitive information configuration implementation, the assembly forMicrosoft.Framework.ConfigurationModel.UserSecrets, through the management of the Assembly, we can put sensitive configuration information in the computer's special directory ofsecrets.jsonfiles, the directory definition rules are as follows:


Windows:%appdata%\microsoft\usersecrets\<applicationid>\secrets.json
Linux: ~/.microsoft/usersecrets/ <applicationid>\secrets.json
Mac: ~/.microsoft/usersecrets/<applicationid>\secrets.json


Let's take the example, first, right-click Solution SelectionManage User Secret, VS will automatically create one for the programapplicationId, and keep it in the project.json file, as follows:


{"
 Usersecretsid": "aspnet5-webdemo01-20150430014447", "
 Webroot": "Wwwroot",
 "version": "1.0.0-*",
}


Then automatically opens%APPDATA%\Microsoft\UserSecrets\aspnet5-WebDemo01-20150430014447\secrets.jsonthe file, and we enter a sample configuration:


{"
 AA": {"
 BB": "CC"
 }
}


We then referenced the above assembly in the Project.json file and then registered it in the same way as the configuration file:


Configuration = new Configuration ()
  . Addjsonfile ("Config.json")
  . Addenvironmentvariables ()
  . Addusersecrets (); Addusersecrets is an extension method for adding sensitive information


You can then call the normal invocation method, as shown in the following example:


var data = configuration["AA:BB"]; Result: CC


In this way, we can place the configuration information of the production environment in a private location.



Custom Configuration Source



With the example above and looking at its architectural design mechanism, we can see that we can actually customize our own configuration sources, such as the configuration information that I want to read the response from the database, so we just define a dbconfigurationsource, and inherits from the Configurationsource, can realize the load overload of the response.


public class Dbconfigurationsource:baseconfigurationsource
{public
 override void Load ()
 {
 // Read all the key/value of the database and assign it to idictionary<string, string> type of Data
 }
}



public class Dbconfigurationsource:baseconfigurationsource
{public
 override void Load ()
 {
 // Read all key/value of the database, save in private variable _data
 } public

 override void Set (string key, String value)
 {
 // Update value/base for database key
 . Set (key, value);

 The public override bool Tryget (string key, out string value) {//
 Gets the value//return base of the key in the private variable _data
 . Tryget (key, out value);

 public override ienumerable<string> Producesubkeys (ienumerable<string> earlierkeys, string prefix, string Delimiter)
 {
 ///private variable _data, returns the response subkeys//return base according to its own mechanism
 . Producesubkeys (Earlierkeys, prefix, delimiter);
 }


After you implement the above class, create an extension method for yourself to add the DB configuration information as follows:


public static class Catsconfigurationextensions
{public
 static Iconfigurationsourcecontainer Adddbconfiguration (this iconfigurationsourcecontainer configuration)
 {
 configuration. ADD (New Dbconfigurationsource ());
 return configuration
 }
}


can be passed. Adddbconfiguration () to add the DB configuration source.



Note that the DB configuration source requires the use of a database connection string, which should be noted (get the connection string from the JSON profile before adding the configuration source).



Configuration information Traversal



In the default configuration source implementation, all classes inherit from Configurationsource, and the information data is stored in the Data property, so if you want to traverse this, you need to convert it to a Configurationsource type before you can use the sample code as follows:


foreach (Var o in Configuration as Configuration)
{
 var source = o as Configurationsource;
 foreach (var key in source). Data.keys)
 {
 Console.WriteLine (key + ":" + source. Data[key]);
 }


Configuration information is directly converted to entity classes



ThereIServiceCollectionis also an extension method on the interface that.Configure<T>IConfigurationconverts the data of the type to an entity class, as defined by the following extension method:


public static Iservicecollection configure<toptions> (this iservicecollection services, IConfiguration config, int order = -1000, String optionsname = "");


For example, if we define an entity as follows:


public class AppSettings
{public
 string Sitetitle {get; set;}
}


The configuration information for the same structure is then defined in theconfig.jsonfollowing example:


{
 "AppSettings": {"Sitetitle":
 "WebDemo01"
 }
}


Then byStartuploading the configuration information in the constructor, we can assign the information to theAppSettingsinstance with the following code:


Services. Configure<appsettings> (Configuration.getsubkey ("AppSettings"));


Used, theApplicationServicesGetRequiredServicemethod can be used, the example is as follows:


var appSettings = app. Applicationservices.getrequiredservice<ioptions<appsettings>> (). Options;


Precautions:



In the configuration information, all key is case-insensitive, that is, key and key are the same. If multiple configuration sources have duplicate keys, the value corresponding to the key in the configuration source that is added later is whichever.IConfigurationGetSubKeysandGetSubKeycan get a list of all the keys for a level (or at the beginning of a hierarchy). BecauseConfigurationit is multiple instances, the code in the example, in which the instance is initialized, is inaccessible toStartupother classes, so if you want to make global access, it's best to save it to a static variable after initialization.



Reference 1:https://github.com/aspnet/configuration
Reference 2:http://blog.jsinh.in/asp-net-5-configuration-microsoft-framework-configurationmodel/


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.