Background
During our development, we will have many different environments, such as Dev, QA, Pre, Pro.
There is a problem regarding how to distinguish the configuration files in different environments.
For example, the connection string. Each environment is different! How can we read it from the configuration files?
Most of the time, we will follow the below screenshot to manage our configuration files.
When we are developing, it's not hard to change the environment by modifying the
launchSettings.json file, so that we can read the matching configuration with different environments.
After publishing our project, we cannot modify the
launchSettings.json file to change the environment! Because the published files do not contain this file!
So, how can we do that?
By the way, all our ASP.NET Core projects are hosted in CentOS 7.x with Jexus.
For more information on how to host ASP.NET Core with Jexus, you can visit my article,
And I will introduce two solutions to handle this case.
Solution #1
Setting the ASPNETCORE_ENVIRONMENT environment variable.
Modify /etc/profile, add the following configuration.
- export ASPNETCORE_ENVIRONMENT=QA
Then, we need to execute the source command to make it available.
After restarting our website, we can find the following logs:
- Hosting environment: QA
- Content root path: /var/www/testweb
- Now listening on: http://127.0.0.1:47372
- Application started. Press Ctrl+C to shut down.
But this way will also give rise to some difficult things. We need to create this environment variable for each virtual machine. Actually, we only allow a system image for our environment(.NET Core, Java,etc.). This way is suitable for no limitation of system images. The second way can help solve the limitation.
Solution #2
Setting hosting environment using command args that allows us to specify the hosting environment at run time using the --environment argument.
- port=80
- root=/ /var/www/testweb
- hosts=*
-
- AppHost={
- cmd=dotnet /var/www/testweb/myweb.dll --environment QA;
- root=/var/www/testweb;
- port=0
- }
After restarting this website, we will find that the same result as the first solution.
- Hosting environment: QA
- Content root path: /var/www/testweb
- Now listening on: http://127.0.0.1:47372
- Application started. Press Ctrl+C to shut down.
This is the recommended solution.
Note
When not using WebHost.CreateDefaultBuilder(args) to create the builder, do not forget to AddCommandLine in your Program.cs.
This is an important step to use command args!
Summary
This article introduces two solutions to handle multiple environments when we host ASP.NET Core.
I hope this will help you!