Interpreting ASP. NET 5 & MVC6 series tutorials (5): Configuration information management, interpreting ASP. NET

Source: Internet
Author: User
Tags key string

Interpreting ASP. NET 5 & MVC6 series tutorials (5): Configuration information management, interpreting ASP. NET

In the previous chapter, we know that the new version of the MVC program has abandoned the original web. config File mechanism, which replaces config. json. Today, we will go into more details about the configuration file.

Basic usage

The configuration information mechanism of the new version is rewritten in the Microsoft. Framework. ConfigurationModel namespace. After rewriting, it not only supports XML format, but also json, ini, and environment variables. In the template example program, if the Startup class constructor contains the following statements:

// Setup configuration sources.Configuration = new Configuration() .AddJsonFile("config.json") .AddEnvironmentVariables();

This statement is used to add the config. json file and environment variable information to the configuration information container for reading. When reading data, you can read data in the form of a SET index or Get method, for example:

var path = Configuration["Path"];var path = Configuration.Get("Path");

Multiple Levels of key names must be separated by colons. For example:

var connString = Configuration.Get("Data:DefaultConnection:ConnectionString");

The code above shows that the configuration example is not a global instance. to read this information elsewhere, you need to save the instance to a Global static variable.

Architecture Design

The new configuration information processing mechanism is more lightweight and cross-platform after rewriting. It can obtain configuration information from multiple data sources instead of sticking to it. config file, and you can even set different configuration information for different environments (development, testing, production. For important entities of the configuration mechanism, see:

Let's talk about the specific functions of these classes one by one:

1.IConfiguration-Instance interface for configuration information.indexer,Get,TryGet,SetAnd other imagesReloadThese methods are used together to obtain key/value-based configuration information.

2.IConfigurationSource-This interface unifies the interface methods used by each configuration source, suchTryGet,SetAnd the most importantloadTo load the information to the configuration subsystem.

3.IConfigurationSourceContainer-One container for all Configuration source information. This container allows you to load Configuration information of various Configuration sources on a single Configuration instance. This interface has only oneAddMethod to addIConfigurationSourceConfiguration source information.

4.Configuration-This class implementsIConfigurationInterfaces andIConfigurationSourceContainerDoes not save configuration information of all types based on key/value.

5.ConfigurationExtensions-The extension method is used to quickly load configuration information, as shown in figureAddCommandLine,AddIniFile.

In the Microsoft. Framework. ConfigurationModel namespace, there are currently six different types of configuration source types available, as shown below:

1.MemoryConfigurationSource-The configuration source does not currently have the built-in add/load extension method (for exampleAddMemoryConfiguration), But you can load a set of key/value types to achieve this purpose (for exampleIEnumerable<KeyValuePair<string, string>>Type ).

2.IniFileConfigurationSource-This configuration source can load INI file configuration information in key/value format to the configuration system.

3.CommandLineConfigurationSource-Load the command line parameter information when the program starts to the configuration system.

4.EnvironmentVariablesConfigurationSource-Load the environment variable information of the operating system to the configuration system. In Azure Website, environment variables can be set on the web interface for convenient management.

5.JsonConfigurationSource-Load the json file information to the configuration system.

6.XmlconfigurationSource-Load the xml file information to the configuration system.

Detailed usage

First, because the Configuration System is multi-instance, you must declare an example before each use. The Code is as follows:

IConfiguration configuration = new Configuration();

Add MemoryConfigurationSource

The IConfigurationSourceContainer does not have an extended method for quickly loading configuration information for MemoryConfigurationSource. To load configuration information of this type, 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 Method var someConfiguration1 = Configuration ["mem-key1"]; var someConfiguration2 = Configuration. get ("mem-key2 ");

Add IniFileConfigurationSource

The configuration information of the IniFileConfigurationSource type can be loaded using the extension method. The Code is as follows:

var configuration = new Configuration().AddIniFile("path\\to\\your\\configuration-ini-file.ini");

The format template of the INI file is as follows:

[ini-sec]ini-key1=value-aini-key2=value-b[ini-sec2]ini-key1=value-cini-key2=value-d

[Ini-sec] is the name of the custom configuration section. You can configure multiple key/value items under each configuration section. The value is the same as that in the basic example. The layers (in this example, the configuration section and the key) must be separated by colons. The example is as follows:

var someConfiguration1 = Configuration["ini-sec:ini-key1"];var someConfiguration2 = Configuration.Get("ini-sec2:ini-key2");

Add CommandLineConfigurationSource

When the program uses the k run name, the input parameters can be read through the configuration source, or you canAddCommandLineThe extension method is manually added, for example:

var configuration = new Configuration().AddCommandLine(new string[] { "key1=value1", "key2=value2", "@key3=value3" });

In the preceding example, each string is in the key/value format and can use less than special symbols such as $ and. For these key values, you can also useswitchMappingsParameter ConstructorCommandLineConfigurationSourceClass to map some keys,switchMappingsThe data types and examples of parameters are as follows:

var mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase){ { "key1", "tom1" }, { "key2", "tom2" },};

Because there is no extension method for the CommandLineConfigurationSource class, we still need to instantiate the class and add it to the configuration container. The Code is as follows:

((IConfigurationSourceContainer)Configuration).Add(new CommandLineConfigurationSource(commandLineArguments, switchMappings: mappings));

After the above code is executed, the values of the following two keys are the same when obtaining the configuration value:

Var value1 = Configuration. get ("key1"); var value2 = Configuration ["tom1"]; // the value of the key tom1 is actually the value of key1, because tom1 is the ing of key1.

During the key ing, the new ing key string cannot contain the "/" character. Otherwise, an exception is reported, and the same key cannot be input twice. Otherwise, when the configuration information is loaded abnormally, if duplicate keys exist, the value of the last key overwrites the value of the previous key. When loading CommandLine configuration information, if a key string uses-as the prefix, you must use switchMapping to map a new key to the old key. Otherwise, an error occurs.

Add EnvironmentVariablesConfigurationSource

ironmentVariablesConfigurationSourceYou can add the environment variables of the operating system to the configuration system, and you can also customize these environment variables, such as during VS development and debugging, you can add some key/value in the following interface:

The values are as follows:

var someConfiguration1 = Configuration["env_var_key1"];var someConfiguration2 = Configuration["env_var_key2"];

In addition, this configuration source also supports Azure environment variables and connection strings, so you can also set MSSQL, MYSQL, and custom link strings on the Azure interface, however, these link strings must 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 for defining a development environment is as follows:

Key => SQLCONNSTR_devlocalValue => Server=localhost;Database=test_db;Trusted_Connection=True;

After loading the information in the form of AddEnvironmentVariables (), we can access this information as follows:

var connString = Configuration["Data:devlocal:ConnectionString"];

That is to say, in Azure, the key of the environment variable is converted to a format such as Data: Custom identifier: ConnectionString. If your key is not a custom key (CUSTOMCONNSTR_), You can obtain the provider name of the connection string in the following way, for example:

Var providerName = Configuration ["Data: devlocal: ProviderName"]; // return value: System. Data. SqlClient

EnvironmentVariablesConfigurationSourceIn addition, a prefix filtering method is also provided to load part of information, such:

((IConfigurationSourceContainer)Configuration).Add(new EnvironmentVariablesConfigurationSource("Data:"));

In this way, the Data in the key value can be omitted when the information is obtained. The example is as follows:

var conn1 = Configuration["devlocal:ConnectionString"];var conn2 = Configuration["devlocal:ProviderName"];

Add JsonConfigurationSource

At the beginning of the article, we can see the loading of the json configuration file. to load this file, you only need to use.AddJsonFile("test.json")Extension Method, but do not forget to reference Microsoft. Framework. ConfigurationModel. json assembly in dependencies of project. Json.

For example, if the content of your config. json file is as follows:

{ "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" } }}

Then you can use the following method to access the link string:

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

Add XmlconfigurationSource

XmlconfigurationSourceThe configuration source and JsonConfigurationSource are similar to the configuration source. The Microsoft. Framework. ConfigurationModel. Xml assembly is referenced first, and then.AddXmlFile("test.xml").

If the content of your configuration file test. xml is as follows:

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

There are some differences (root node will be ignored ):

Var s1 = Configuration ["key1"]; // return Jsinhvar s2 = Configuration ["key2: subkey2"]; // return Hello world

However, you must note that the general key cannot be repeatedly declared, and the following files will encounter errors during reading.

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

Sensitive information configuration (New Function in RC)

After the release of the RC version, Microsoft added a sensitive information configuration implementation.Microsoft.Framework.ConfigurationModel.UserSecretsThrough the management of this Assembly, we can put sensitive configuration information under the special directory of the computersecrets.jsonFile. The directory definition rules are as follows:

Windows: %APPDATA%\microsoft\UserSecrets\<applicationId>\secrets.jsonLinux: ~/.microsoft/usersecrets/<applicationId>\secrets.jsonMac: ~/.microsoft/usersecrets/<applicationId>\secrets.json

For example, right-click the solution and selectManage User Secret, VS automatically createsapplicationIdAnd keep it in the project. json file. The example is as follows:

{ "userSecretsId": "aspnet5-WebDemo01-20150430014447", "webroot": "wwwroot", "version": "1.0.0-*",}

Then it will automatically open%APPDATA%\Microsoft\UserSecrets\aspnet5-WebDemo01-20150430014447\secrets.jsonFile, we enter an example Configuration:

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

Then, we reference the above assembly in the project. json file, and then register it in a unified way through the configuration file. The Code is as follows:

Configuration = new Configuration (). AddJsonFile ("config. json"). AddEnvironmentVariables (). AddUserSecrets (); // AddUserSecrets is an extension method for adding sensitive information.

Then you can call a common call method, for example:

Var data = Configuration ["AA: BB"]; // result: CC

In this way, we can place the configuration information of the production environment in the Privacy position.

Custom configuration Source

Through the above examples and viewing its architecture design mechanism, we can find that we can also customize our own configuration source, for example, I want to read the response configuration information from the database, we only need to define a DBConfigurationSource and inherit it from ConfigurationSource, so we can implement the Load overload of the response.

Public class DBConfigurationSource: BaseConfigurationSource {public override void Load () {// read all the keys/Values of the database and assign them to IDictionary <string, string> Data }}

If you do not save the Data in the Data attribute, You need to implement the following reloads to obtain the response value from your private dataset, such as from the cache. The example is as follows:

Public class DBConfigurationSource: BaseConfigurationSource {public override void Load () {// read all the keys/Values of the database and store them in the private Variable _ data} public override void Set (string key, string value) {// update the value of the database key // base. set (key, value);} public override bool TryGet (string key, out string value) {// obtain the value corresponding to the key from the private Variable _ data // return base. tryGet (key, out value);} public override IEnumerable <string> ProduceSubKeys (IEnumerable <string> earlierKeys, string prefix, string delimiter) {// Private Variable _ data, return the response SubKeys // return base based on your own mechanism. produceSubKeys (earlierKeys, prefix, delimiter );}}

After the above classes are implemented, create an extension method for yourself to add DB configuration information. The Code is as follows:

public static class CatsConfigurationExtensions{ public static IConfigurationSourceContainer AddDBConfiguration(this IConfigurationSourceContainer configuration) { configuration.Add(new DBConfigurationSource()); return configuration; }}

You can use. AddDBConfiguration () to add the DB configuration source.

Note: The DB configuration source must use the database connection string. Note that (you can obtain the connection string from the json configuration file before adding the configuration source ).

Configuration Information Traversal

In the default configuration source implementation, all classes are inherited from ConfigurationSource and information Data is saved in the Data attribute. Therefore, to traverse the Data, you need to convert it to the ConfigurationSource type for use. The sample code is 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 object class

InIServiceCollectionThere is also an extension method on the interface..Configure<T>You can set the typeIConfigurationTo an object class. The extension method is defined as follows:

public static IServiceCollection Configure<TOptions>(this IServiceCollection services, IConfiguration config, int order = -1000, string optionsName = "");

For example, if we define an object as follows:

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

Thenconfig.jsonDefines the configuration information of the same structure, for example:

{ "AppSettings": { "SiteTitle": "WebDemo01" }}

ThenStartupAfter the constructor loads the configuration information, we can assign this informationAppSettingsThe Code is as follows:

services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));

UseApplicationServicesOfGetRequiredServiceMethod, for example:

var appSettings = app.ApplicationServices.GetRequiredService<IOptions<AppSettings>>().Options;

Note:

In the configuration information, all keys are case-insensitive, that is, keys and keys are the same. If multiple configuration sources have duplicate keys, the value of the key in the configuration source added later prevails.IConfigurationUnderGetSubKeysAndGetSubKeyYou can obtain a list of all keys at a level (or starting with a level. BecauseConfigurationIs multi-instance, so according to the code in the example, the instance inStartupAfter initialization, other classes cannot be accessed. Therefore, if you want to perform global access, it is 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.