ASP.NET Core project starts, the default execution order is: Host Host -> Read Configuration -> Log Settings -> Registration Service (DI) -> Add Middleware -> WebHost Listening -> Background Work Startup.
Configuration loading and reading are at the very beginning of the startup process. Microsoft's profile in ASP.NET Core:The hyperlink login is visible.
Review:
Host.CreateDefaultBuilder method, provide the default configuration for the app in the following order:
- ChainedConfigurationProvider: Add an existing one as a source. In the default configuration example, add the host configuration and set it as the first source for the application configuration.
- Use appsettings.json appsettings.json.
- Use the JSON configuration provider via appsettings: json provided. For example, appsettings. Production.json and appsettings. Development.json。
- App secrets when the app runs in the environment.
- Use environment variables configuration providers to provide through environment variables.
- Using the command line configuration provider is provided through command line parameters.
The source code is as follows:
Source code address:The hyperlink login is visible.
As you can see from the code, the program acquisition configuration priority is:appsettings.json -> appsettings.environment.json -> environment variables -> command-line arguments。 We test according to priority.
Create a new console method to return all configuration information, the code is as follows:
First, appsettings.json the configuration file, as follows:
New appsettings. Test.json configuration, as follows:
Try starting the project and see the configuration of WebConfig:Name and WebConfig:Date, as shown in the following image:
{"Key":"WebConfig:Name","Value":"itsvse.com"},{"Key":"WebConfig:Date","Value":"2021"}
Locate Properties ->launchSettings.jsonfile, modify the ASPNETCORE_ENVIRONMENT environment configuration to Test, as follows:
At this time, the procedurewill read the appsettings. Test.json configuration, try to restart the project, findWebConfig:Name 已经覆盖了, as shown in the figure below:
{"Key":"WebConfig:Name","Value":"itsvse.com test"},{"Key":"WebConfig:Date","Value":"2021"}
Modify the launchSettings.json file again and set the value of WebConfig:Name via the environment variable, the code is as follows:
Note: Modify the value of WebConfig:Name for the environment variable, the variable name is: WebConfig__Name (The middle is separated by a double underscore)
Try restarting the project and find the value of WebConfig:Name,It has been overwritten by the value set by the environment variable, as shown in the figure below:
Try to modify the default value via the command line, and start the command as follows:
As shown below:
Test the priority of configuration keys with practice, and that's it.
|