Categories
Uncategorized

ASP.NET Core 2.2:. Twenty-two diversity configuration

Most applications are inseparable from the configuration This chapter describes the mechanism ASP.NET Core in several common configurations and internal system implementation. (ASP.NET Core Series Catalog)

When it comes to configuration, the first impression is probably the “.config” type of xml file or “.ini” type of ini files in ASP.NET Core, a common configuration file type is JSON. For example appsettings.json and appsettings.Development.json two files in the root directory of the project. In fact, ASP.NET Core supports a variety of configurations, in addition to ways of using JSON file, also supports memory, and other command-line mode.

First, papers

This is the most common way, ASP.NET Core supports a variety of configuration file formats, such as file common JSON, XML, INI and other formats.

First look at the project default configuration file created appsettings.json, its default content as follows:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

This file is automatically loaded when the system starts (loads occur in CreateWebHostBuilder method Program file, the next section will explain in detail), the default configuration is primarily aimed at the Log.

For example, we need to set a theme in the configuration file, such as color and style. Add the following to the end of the file:

 "Theme": {
    "Name": "Blue",
    "Color": "#0921DC"
  }

Provided by the subject systems and color values ​​corresponding to such code. So this is how the value is to obtain and use it? The default HomeController for example, “GetConfiguration” new one called the Action to demonstrate the value of acquired Configuration. code show as below:

privatereadonlyIConfiguration _configuration;
publicHomeController(IConfiguration configuration) { _configuration
= configuration; } publicContentResult GetConfiguration() { returnnewContentResult() { Content = $"Theme Name:{ _configuration["Theme:Name"] },Color:{_configuration["Theme:Color"]}"}; }

In the constructor dependency injection by way of a IConfiguration obtained, and the value set in appsettings.json Action by the acquired IConfiguration this. As can be seen, when the value of the acquisition, through the “:” symbol to reflect the hierarchy embodied in JSON. For example to get the value “Color”, the corresponding expression for “_configuration [” Theme: Color “]”. This is because the entire process is JSON Key-Value format as one of two values ​​according to the present embodiment “Theme” will be broken down into the following format:

Key

Value

Theme:Name

Blue

Theme:Color

#0921DC

There are two instructions, the first, “Key” is not case sensitive, i.e. written as “theme: color” is equivalent; second, agreed “Value” value is a string format.

In addition to obtaining the above example embodiment, may also be obtained by GetValue method.

_configuration.GetValue<string>("Theme:Color","#000000")

Meaning that the acquired value into a string type, if the failure to obtain the default value “# 000000” is returned.

This example demonstrates the contents of the system default appsettings.json file is automatically loaded, then how to customize the contents of the JSON file an application to the configuration of the system go?

Create a new file named “Theme.json”, the same preset and then a red theme, as follows:

{
  "Theme": {
    "Name": "Red",
    "Color": "#FF4500"
  }
}

Because of this custom “Theme.json” will not be automatically loaded, you need to manually add it to configure the system to go, he said speaking at the launch of the application system when the configuration is in CreateDefaultBuilder method Program file loading, can continue the method continues by ConfigureAppConfiguration disposed thereafter. For example the following code:

publicstaticIWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext,config)=> {
        config.SetBasePath(Directory.GetCurrentDirectory());
        varpath = Path.Combine(Directory.GetCurrentDirectory(), "Theme.json");
        config.AddJsonFile(path, optional: false, reloadOnChange: true);
    })
    .UseStartup();
}

The method provided by the first group SetBasePath path, and then add “Theme.json” files AddJsonFile method that has three parameters, the first position is a “Theme.json” where, if the second optionally set the file the third set when the file has been modified, whether to automatically reload the file.

Access home / GetConfiguration again, the returned results are as follows:

Theme Name:Red,Color:#FF4500

This is because the value Theme.json Theme file after the added coverage in the Theme value appsettings.json file. This involves a variety of ways to configure settings priority issues, he will speak in the next section.

Having an example of the JSON file format used to configure, and then look at how to use the INI format. Create a new file named Theme.ini, in order not to cover Theme previously set, the present embodiment will be changed to Theme ThemeGreen.

[ThemeGreen]
Name=Green
Color=#76EE00

Add the method by ConfigureAppConfiguration this configuration INI file to go.

var pathIni = Path.Combine(Directory.GetCurrentDirectory(), "Theme.ini");
config.AddIniFile(pathIni, optional: false, reloadOnChange: true);

Action read modify configuration Key, corresponding to the Theme ThemeGreen:

publicContentResult GetConfiguration()
{
    returnnewContentResult() { Content = $"Theme Name:{ _configuration["ThemeGreen:Name"] },Color:{_configuration.GetValue("ThemeGreen:Color", "#000000")}"};
}

Access home / GetConfiguration again, the returned results are as follows:

Theme Name:Green,Color:#76EE00

The application of the above two file formats and the INI JSON, in addition to the two different file formats as well as different methods used when added to the configuration (and were used AddJsonFile AddIniFile method), both in the use of the other links are it’s the same. Similarly, for the XML file format, there is a corresponding AddXmlFile method, application and other aspects of JSON, INI files is the same, here is no longer described as an example.

Second, the catalog file

In addition to the use of a JSON, INI files, and XML formats such commonly used, but also may be designated as the data source directory and file configuration.

For example there are folders s, below which 2.txt 1.txt and two files, file contents are s1 and s2, as in FIG. 1

 

figure 1

This can be a directory and file as the data source configuration, the same can only be added in ConfigureAppConfiguration method, see the following code:

var pathFile = Path.Combine(Directory.GetCurrentDirectory(), "s");
config.AddKeyPerFile(directoryPath: pathFile, optional: true);

Action by a test:

publicContentResult GetFileConfiguration()
{
     returnnewContentResult() { Content = $"1.txt:{_configuration["1.txt"]}, 2.txt:{_configuration["2.txt"]}"};
}

Return result:

1.txt:s1,2.txt:s2

Such a method is to be seen filename as two s file folder for Key, as the contents of the file Value.

Third, the command line

By the time the application start command, at the command line by adding a Key-Value manner as the data source configuration, for example, run the following command to start the application:

dotnet run key1=value1 key2=value2

Access defined as follows Action:

publicContentResult GetCommandConfiguration()
{
    returnnewContentResult() { Content = $"key1:{_configuration["key1"]}, key2:{_configuration["key2"]}"};
}

Return result:

key1:value1,key2:value2

This is due to add a call to the command line parameter in the default WebHost.CreateDefaultBuilder (args) method, if the need to continue to add ConfigureAppConfiguration method, just call config.AddCommandLine (args) method to the method in South Africa.

Fourth, the environment variable

In WebHost.CreateDefaultBuilder (args) method, in addition to the load command line parameters, will load the data environment variable. Herein include environment variables system environment variable, for example, FIG. 2

 

figure 2

Environment variable “variable” and “value” is read as Key and Value configuration.

In addition to reading system environment variables may be added in the properties of the project, such as adding the properties of the project, for example, Figure 3:

 

image 3

In addition to the familiar environment variable named ASPNETCORE_ENVIRONMENT, but also added a Key here is TestKey, Value for the TestValue environment variables.

Adding an Action test:

publicContentResult GetEnvironmentVariables()
{
    returnnewContentResult() { Content = $"TestKey:{_configuration["TestKey"]}, OS:{_configuration["OS"]}"};
}

Read respectively in Figures 2 and 3 are two variables environment, access to the Action this, the result is returned:

TestKey:TestValue,OS:Windows_NT 

Fifth, the memory object

The above examples are some of the external data source configuration read and converted into the Key-Value format, whether the code can be created directly in the application of some of the Key-Value and add value to the configuration go? It is certainly possible. Common is the Dictionary, and create a new Dictionary code is as follows:

public static readonly Dictionary<string, string> dict = newDictionary<string, string> { { "ThemeName", "Purple"},{"ThemeColor", "#7D26CD"} };

In the method ConfigureAppConfiguration added into the configuration:

config.AddInMemoryCollection(dict);

Action to create a new test:

publicContentResult GetMemoryConfiguration()
{
     returnnewContentResult() { Content = "ThemeName:{_configuration["ThemeName"]}, ThemeColor:{_configuration["ThemeColor"]}"};
}

Return result:

ThemeName:Purple,ThemeColor:#7D26CD

 

 

 

Leave a Reply