In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
The editor will share with you the example analysis of Configuration configuration information management in ASP.NET5 and MVC6. I hope you will get something after reading this article. Let's discuss it together.
Basic usage
The new version of the configuration information mechanism is rewritten under the Microsoft.Framework.ConfigurationModel namespace, which supports not only XML format, but also json, ini, environment variables, and so on. Within the constructor of the Startup class in the template sample program, for example, there is the following statement:
/ / Setup configuration sources.Configuration = new Configuration () .AddJsonFile ("config.json") .AddenvironmentVariables ()
The purpose of this statement is to add the config.json file and environment variable information to the configuration information container for reading. When reading, you can read it in the form of a collection index or the Get method. An example is as follows:
Var path = Configuration ["Path"]; var path = Configuration.Get ("Path")
For multi-level key key reading, you need to separate multiple level names with colons, as shown in the following example:
Var connString = Configuration.Get ("Data:DefaultConnection:ConnectionString")
As you can see from the above code, the configuration example is not a global instance, so if you want to read this information elsewhere, you need to save the instance on a global static variable.
Architecture design
The new configuration information handling mechanism, after rewriting, is more lightweight and cross-platform, and can obtain configuration information from multiple data sources without having to stick to .config files. and you can even set different configuration information for different environments (development, testing, production). The important entities of the entire configuration mechanism are shown in the following figure:
Let's talk about the specific functions of these classes one by one:
1.IConfiguration-an instance interface of configuration information on which indexer, Get, TryGet, Set, and other methods like Reload are used to obtain key/value-based configuration information.
2.IConfigurationSource-this interface unifies the interface methods used by various configuration sources, such as TryGet, Set, and, most importantly, the load method to read configuration information in order to load the information into the configuration subsystem.
3.IConfigurationSourceContainer-A container for all configuration source information that allows configuration information for various configuration sources to be loaded on a single Configuration instance. There is only one Add method for this interface to add IConfigurationSource-based configuration source information.
4.Configuration-this class implements the IConfiguration interface and the IConfigurationSourceContainer interface and does not save all types of configuration information based on key/value.
5.ConfigurationExtensions-extension method for quickly loading configuration information, such as AddCommandLine, AddIniFile, and so on.
There are currently six different types of configuration source types that can be used under the Microsoft.Framework.ConfigurationModel namespace, as follows:
1.MemoryConfigurationSource-there are currently no built-in add/load extension methods (such as AddMemoryConfiguration) for this configuration source, but you can load collections of type key/value to do this (such as type IEnumerable).
2.IniFileConfigurationSource-the configuration source that loads INI file configuration information based on key/value format into the configuration system.
3.CommandLineConfigurationSource-loads the command line parameter information when the program starts 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 quite convenient to manage.
5.JsonConfigurationSource-loads the information from the json file into the configuration system.
6.XmlconfigurationSource-loads the information from the xml file into the configuration system.
Detailed usage
First of all, because the configuration system is multi-instance, an example should be declared before each use, as follows:
IConfiguration configuration = new Configuration ()
Add MemoryConfigurationSource
Since there is no extension method defined on IConfigurationSourceContainer for MemoryConfigurationSource to quickly load configuration information, if you want to load this type of configuration information, you need to add it as follows:
((IConfigurationSourceContainer) Configuration) .add (new MemoryConfigurationSource (new List {new KeyValuePair ("mem-key1", "mem-value1"), new KeyValuePair ("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 by the extension method, as follows:
Var configuration = new Configuration () .AddIniFile ("path\\ to\\ your\\ configuration-ini-file.ini")
The format template of ini file is as follows:
[ini-sec] ini-key1=value-aini-key2=value-b [ini-sec2] ini-key1=value-cini-key2=value-d
Here [ini-sec] is the name of the custom configuration section, and multiple key/value items can be configured under each configuration section. The value is taken in the same way as in the basic example, which is separated by colons between levels (in this case, between the configuration section and key). The example is as follows:
Var someConfiguration1 = Configuration ["ini-sec:ini-key1"]; var someConfiguration2 = Configuration.Get ("ini-sec2:ini-key2")
Add CommandLineConfigurationSource
The parameters passed when the program uses k run naming can be read from the configuration source, or you can add them manually through the AddCommandLine extension method, as shown in the following example:
Var configuration = new Configuration () .AddCommandLine (new string [] {"key1=value1", "key2=value2", "@ key3=value3"})
Each string in the above example should be in key/value format and can use less than special symbols such as $, /, and so on. For these key values, you can also use the CommandLineConfigurationSource class with the switchMappings parameter constructor to map the data types and examples of some key,switchMappings parameters as follows:
Var mappings = new Dictionary (StringComparer.OrdinalIgnoreCase) {{"key1", "tom1"}, {"key2", "tom2"},}
Since 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 executing the above code, when getting the configuration value, the following two key values are the same:
Var value1 = Configuration.Get ("key1"); var value2 = Configuration ["tom1"]; / / the value of this key is actually the value of key1, because tom1 is the mapping of key1
During mapping, the "/" character cannot be included in the new mapping key string, otherwise the same key cannot be passed twice, otherwise the configuration information will be loaded with an exception. If there is a duplicate key, the value of the latter key will overwrite the value of the previous key. When loading CommandLine configuration information, if a key string is prefixed with -, you must use switchMapping to map a new key to the old key, otherwise an error will occur.
Add EnvironmentVariablesConfigurationSource
IronmentVariablesConfigurationSource can add the environment variables of the operating system to the configuration system, and you can also customize these environment variables. For example, when developing and debugging VS, 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, the configuration source also supports Azure environment variables and connection strings, so you can also set MSSQL, MYSQL, custom link strings, and so on in the Azure interface, but these link strings need to start with the following:
1.MySQL = > MYSQLCONNSTR_
2.MS SQL = > SQLCONNSTR_
3.SQL Azure DB = > SQLAZURECONNSTR_
4.Custom DB = > CUSTOMCONNSTR_
For example, the key/value that defines a development environment is as follows:
Key = > SQLCONNSTR_devlocalValue = > Server=localhost;Database=test_db;Trusted_Connection=True
After load the information in the form of AddEnvironmentVariables (), we can access the information in the following ways:
Var connString = Configuration ["Data:devlocal:ConnectionString"]
That is, 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 (starting with CUSTOMCONNSTR_), you can get the provider name of the connection string as follows, as shown below:
Var providerName = Configuration ["Data:devlocal:ProviderName"]; / return: System.Data.SqlClient
EnvironmentVariablesConfigurationSource also provides a prefix filtering method to load some information, such as:
((IConfigurationSourceContainer) Configuration) .add (new EnvironmentVariablesConfigurationSource ("Data:"))
In this way, when you get the information again, the Data: in the key value can be omitted. 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 the loading of the json configuration file, which only needs to be loaded using the .AddJsonFile ("test.json") extension method, but don't forget to reference the Microsoft.Framework.ConfigurationModel.Json assembly in project.json 's dependencies first.
For example, if your config.json file contains something like this:
{"Data": {"DefaultConnection": {"ConnectionString": "Server= (localdb)\\ mssqllocaldb;Database=aspnet5-WebApplication1-64357659-de50-4b1e-b005-30310e7ee1efmittance TrustedConnectionistMultipleActiveResultSettrue"}, "EntityFramework": {"ApplicationDbContext": {"ConnectionString": "Data:DefaultConnection:ConnectionString"}
Then you can access the link string in the following ways:
Var conn = Configuration ["Data:DefaultConnection:ConnectionString"]
Add XmlconfigurationSource
The XmlconfigurationSource configuration source is similar to the JsonConfigurationSource configuration source by first referencing the Microsoft.Framework.ConfigurationModel.Xml assembly and then calling .AddXmlFile ("test.xml").
If your profile test.xml contains the following:
Jsinh
To get the form, there is a slight difference (the root node root is ignored):
Var S1 = Configuration ["key1"]; / / return Jsinhvar S2 = Configuration ["key2:subkey2"]; / / return Hello world
Note, however, that generic key cannot be declared repeatedly, and the following files will make errors when reading.
Jsinh
Sensitive information configuration (new in RC version)
After the release of the RC version, Microsoft has added a sensitive information configuration implementation, the assembly is Microsoft.Framework.ConfigurationModel.UserSecrets. Through the management of this assembly, we can put the sensitive configuration information in the secrets.json file in the computer's special directory. The directory definition rules are as follows:
Windows:% APPDATA%\ microsoft\ UserSecrets\\ secrets.jsonLinux: ~ / .microsoft/usersecrets/\ secrets.jsonMac: ~ / .microsoft/usersecrets/\ secrets.json
First of all, right-click the solution and select Manage User Secret,VS to automatically create an applicationId for the program and keep it in the project.json file. The example is as follows:
{"userSecretsId": "aspnet5-WebDemo01-20150430014447", "webroot": "wwwroot", "version": "1.0.0Murray *",}
Then the% APPDATA%\ Microsoft\ UserSecrets\ aspnet5-WebDemo01-20150430014447\ secrets.json file is automatically opened, and we enter a sample configuration:
{"AA": {"BB": "CC"}}
Then, we reference the above assembly in the project.json file, and then register it in a uniform way of the configuration file, as follows:
Configuration = new Configuration () .AddJsonFile ("config.json") .AddenvironmentVariables () .AddUserSecrets (); / / AddUserSecrets is an extension method to add sensitive information
Then you can call it like a normal calling method, as shown in the following example:
Var data = Configuration ["AA:BB"]; / / result: CC
In this way, we can put the configuration information of the production environment in a private location.
Custom configuration source
Through the above example and looking at the architecture design mechanism, we can find that, in fact, we can also customize our own configuration source. For example, if I want to read the configuration information of the response from the database, all we have to do is define a DBConfigurationSource and inherit it from ConfigurationSource to realize the Load overload of the response.
Public class DBConfigurationSource: BaseConfigurationSource {public override void Load () {/ / reads all the key/value in the database and assigns them to Data data of type IDictionary}}
If you do not save the data in the Data attribute, you also need to implement the following overloads to get the response value from your own private data collection, such as from the cache, as shown below:
Public class DBConfigurationSource: BaseConfigurationSource {public override void Load () {/ / read all the key/value in the database and save it in the private variable _ data} public override void Set (string key, string value) {/ / update the value / / base.Set (key, value) corresponding to the database key;} public override bool TryGet (string key, out string value) {/ / obtain the value / / return base.TryGet (key, out value) corresponding to key from the private variable _ data } public override IEnumerable ProduceSubKeys (IEnumerable earlierKeys, string prefix, string delimiter) {/ / private variable _ data, return the SubKeys / / return base.ProduceSubKeys (earlierKeys, prefix, delimiter) of the response according to your own mechanism;}}
After implementing the above class, create an extension method for yourself to add DB configuration information, as follows:
Public static class CatsConfigurationExtensions {public static IConfigurationSourceContainer AddDBConfiguration (this IConfigurationSourceContainer configuration) {configuration.Add (new DBConfigurationSource ()); return configuration;}}
You can add the DB configuration source through .AddDBConfiguration ().
Note that the DB configuration source requires the use of a database connection string (you can get the connection string from the json configuration file before adding the configuration source).
Configuration information traversal
In the default configuration source implementation, all classes inherit from ConfigurationSource and store the information data in the Data property, so if you want to traverse the data, you need to convert it to a ConfigurationSource type before you can use it. The example 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 entity classes
There is also an extension method on the IServiceCollection interface. Configure converts data of type IConfiguration into an entity class, which is defined as follows:
Public static IServiceCollection Configure (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;}}
Then define a configuration information with the same structure in config.json. The example is as follows:
{"AppSettings": {"SiteTitle": "WebDemo01"}}
Then after the configuration information is loaded in the constructor of Startup, we can assign this information to the AppSettings instance as follows:
Services.Configure (Configuration.GetSubKey ("AppSettings"))
When using it, you can use the GetRequiredService method of ApplicationServices. The example is as follows:
Var appSettings = app.ApplicationServices.GetRequiredService () .Options
Note:
In the configuration information, all key are case-insensitive, that is, key and KEY are the same. If multiple configuration sources have duplicate key, the value of key in the last configuration source added later will prevail. GetSubKeys and GetSubKey under IConfiguration can get all the key lists at (or beginning with) a certain level. Because Configuration is multi-instance, according to the code in the example, after the instance is initialized in Startup, other classes cannot be accessed, so if you want to do global access, it is best to save it to a static variable after initialization.
After reading this article, I believe you have some understanding of "sample Analysis of Configuration configuration Information Management in ASP.NET5 and MVC6". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.