当前位置:网站首页>ASP. Net and ASP NETCORE multi environment configuration comparison
ASP. Net and ASP NETCORE multi environment configuration comparison
2022-04-23 03:06:00 【Dotnet cross platform】
Preface
Multi environment configuration should be familiar , The most common is Debug and Release, For example, the following figure shows a new asp.net project , The configuration file deployment consists of three files 
as far as I am concerned , Most companies have never edited Web.Debug.config and Web.Release.config, One Web.config Change the file to switch different configurations , Very troublesome .
asp.net Multi environment configuration under
Even if you double-click to open Web.Debug.config and Web.Release.config Any one of them , Look at the notes inside .
Web.Debug.config
<?xml version="1.0" encoding="utf-8"?>
<!-- About using Web.config Conversion details , Please visit https://go.microsoft.com/fwlink/?LinkId=301874 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--
In the following example ,“SetAttributes” The conversion will change
“connectionString” Value , Only in “Match” The locator found a value of “MyDB” Of
characteristic “name” When using “ReleaseSQLServer”.
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
-->
<system.web>
<!--
In the following example ,"Replace" The conversion will replace Web.config Of documents
Whole <customErrors> section .
Please note that , Because in <system.web> There is only one under the node
customErrors section , So there is no need to use "xdt:Locator" attribute .
<customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/>
</customErrors>
-->
</system.web>
</configuration>
Microsoft wants you to use it , Give not only examples , With detailed notes .
The most commonly used appSettings How to configure
Web.config // development environment
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="MyKey" value="Myvalue" />
</appSettings>
Web.Release.config // Release Environmental Science
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="MyKey" value="Releasvalue" xdt:Transform="Replace" xdt:Locator="Match(key)" />
</appSettings>
After this configuration , Read... During native development MyKey The value of is Myvalue, When publishing the production environment, the value is Releasvalue.
Follow the above configuration , Try publishing it locally .
After publishing successfully , Open the published Web.config file , We found that in the development environment Web.config The corresponding value in is replaced .
How to add additional environment configuration
occasionally Debug and Release The two environments can't meet our needs , More environment configurations need to be added .
Open the menu to generate --> Configuration manager , Create a new one TEST1 Environmental Science 
And then right-click Web.config choice Add configuration transformation ( The fourth one )
It will automatically generate a Web.TEST1.config file , Add a configuration in this environment to override the development configuration 
Change the configuration of the publication 
Open... After successful publishing Web.config file 
The effect is consistent with the expectation .
aspnetcore Multi environment configuration under
aspnetcore The configuration file in is deleted appsettings.json replaced ,.NET Core The configuration in is performed using one or more configuration providers . Configuration providers use various configuration sources to read configuration data from key value pairs :
What is a configuration provider
The following table shows .NET Core Apply the available configuration providers .
| Provider | Configuration is provided through the following objects |
|---|---|
| Azure Application configuration provider | Azure Application configuration |
| Azure Key Vault Configuration provider | Azure Key Vault |
| The command line configuration provider | Command line arguments |
| Custom configuration provider | Custom source |
| Environment variable configuration provider | environment variable |
| File configuration provider | JSON、XML and INI file |
| Key-per-file Configuration provider | Directory file |
| Memory configuration provider | In memory collection |
| Application of confidential ( Secret Manager ) | Files in the user profile directory |
For details, please refer to .NET Configuration in
https://docs.microsoft.com/zh-cn/dotnet/core/extensions/configuration
The following parts are worth noting 
Focus on : The configuration provider added later will replace the previous key settings appsettings.Development.json Than appsettings.json Post load , Then the later loaded will overwrite the value of the first loaded configuration , No problem !
How to load multiple environment configuration files
In order to thoroughly understand the underlying loading logic , Download the source code to find out .
builder.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
if (env.IsDevelopment())
{
if (!string.IsNullOrEmpty(env.ApplicationName))
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
}
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
default WebHostBuilder, Use environment variables env.EnvironmentName Spliced files are loaded by default Json The configuration file .
This explains why the development phase loads appsettings.Development.json Profile .
VS How to switch the environment during local development
How to modify environment variables EnvironmentName Value is the key to the problem , If you can modify the desired value , Then create a configuration file with the corresponding name .
stay web There is a file in the root directory :Properties/launchSettings.json
There is a configuration for configuring environment variables
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
When developing locally, you only need to create multiple startup configurations , Set different ASPNETCORE_ENVIRONMENT You can switch , The modified launchSettings.json
// launchSettings.json
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:2364",
"sslPort": 44302
}
},
"profiles": {
"Web1": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:7006;http://localhost:5006",
"dotnetRunMessages": true
},
"Web1:Test": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "TEST"
},
"applicationUrl": "https://localhost:7006;http://localhost:5006",
"dotnetRunMessages": true
}
}
}
Web1 and Web1:Test The startup options will be displayed synchronously in VS In startup options , Switch to a Web1:Test rerun routine , Will be loaded appsettings.TEST.json, Effect and appsettings.Development.json No difference .
How to apply different profiles when publishing
In the above, we learned to configure multiple different environment configurations locally for development , If the production environment needs to be released, there are many configurations , How to make the program automatically load different configuration files , After all launchSettings.json Files are only used in development VS With , since launchSettings.json Environment variables can be configured , Without it, we can create environment variables manually . Add environment variables to the operating system, such as :

You can also set the environment value by passing parameters from the command line when the program starts .
But both of them are inconvenient for me , We hope that after the program is released according to different environments , Just execute it directly , Instead of requiring additional configuration or parameter transfer .
EnvironmentName attribute
In the engineering documents of the project EnvironmentName attribute , You can specify the current EnvironmentName value , Add the following code 
Then compiled , Direct operation , You can read appsettings.TEST.json The configuration file .
This configuration will not overwrite launchSettings.json The environment value specified in , But it will affect the post release EnvironmentName value , Thus, you can change the default after publishing EnvironmentName value .
Then after this setting , Isn't it after the release EnvironmentName Value can only be Test, If you want to publish other environments, you need to modify this value before publishing each time , Isn't that troublesome ?
Yes, if there is no other means , That's superfluous , Please look at the chart below. .
Get it. , We only need to configure one more PublishProfile Release documents , Specify different To configure term , Then combine Condition Conditions to control EnvironmentName.
thus , Perfectly realize the selection of different release files according to different environments , Publish the project , The target machine does not need to be configured , Direct operation is the effect we want .
Summary although ASP.NET and ASP.NETCore There are different ways to implement multiple environments , But at the end of the release, we can achieve the same effect , All configurations are one-off , Specify the corresponding when publishing PublishProfile that will do .

版权声明
本文为[Dotnet cross platform]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230301334277.html
边栏推荐
猜你喜欢

Golden nine silver ten interview season, you are welcome to take away the interview questions (with detailed answer analysis)

Service avalanche effect

C#中切片语法糖的使用

Recommend reading | share the trader's book list and ask famous experts for trading advice. The trading is wonderful

Small companies don't make formal offers

tf. keras. layers. Embedding function

MAUI初体验:爽

C# WPF UI框架MahApps切换主题

Array and collection types passed by openfeign parameters

Dynamic sequence table + OJ
随机推荐
Judge whether there is a leap year in the given year
Development notes of raspberry pie (12): start Advantech industrial control raspberry pie uno-220 Kit (I): introduction and operation of the system
Detailed explanation of distributed things
tf. keras. layers. Conv? D function
MAUI初体验:爽
Use split to solve the "most common words" problem
建立与遍历二叉树
Summary of interface automation interview questions for software testing
Vs code setting line feed
Golden nine silver ten interview season, you are welcome to take away the interview questions (with detailed answer analysis)
Due to 3 ²+ four ²= five ², Therefore, we call '3,4,5' as the number of Pythagorean shares, and find the array of all Pythagorean shares within n (including n).
c#语法糖模式匹配【switch 表达式】
利用正反遍历来解决“字符的最短距离”问题
[format] simple output (2)
MYSQL05_ Ordr by sorting, limit grouping, group by grouping
Load view Caton
Opencv reads webcam video and saves it locally
Traversal of l2-006 tree (middle and later order determination binary tree & sequence traversal)
使用栈来解决”迷你语法分析器“的问题
Basic workflow of CPU