Solving Multiple Environments Problem When Host ASP.NET Core With Jexus

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.

Solving Multiple Environments Problem When Host ASP.NET Core With Jexus 

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.
  1. export ASPNETCORE_ENVIRONMENT=QA  
Then, we need to execute the source command to make it available.
  1. source /etc/profile  
After restarting our website, we can find the following logs:
  1. Hosting environment: QA  
  2. Content root path: /var/www/testweb  
  3. Now listening on: http://127.0.0.1:47372  
  4. 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.
  1. port=80  
  2. root=/ /var/www/testweb  
  3. hosts=*  
  4.   
  5. AppHost={  
  6. cmd=dotnet /var/www/testweb/myweb.dll --environment QA;  
  7. root=/var/www/testweb;  
  8. port=0  
  9. }   
After restarting this website, we will  find that the same result as the first solution.
  1. Hosting environment: QA  
  2. Content root path: /var/www/testweb  
  3. Now listening on: http://127.0.0.1:47372  
  4. 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!