Handling Several Environments

In this lesson, we will learn how to handle the various environments an ASP.NET Core application passes through before being deployed to production.

All applications pass various testing and validation steps before being deployed to production. They are first run during development. During this stage, unit and integration tests are executed at each build on the chosen source control. They are then deployed to various staging environments, for beta-testing, and validation of the final release candidate.

Being aware of the environment it is running in, the application can adapt its settings to that specific environment. This is necessary as the application must use different database connection strings and different logging and error settings in different environments.

Defining environments

When an ASP.NET Core application starts, it reads the ASPNETCORE_ENVIRONMENT environment variable that should contain a string representing the environment it is running in. Once loaded ASPNETCORE_ENVIRONMENT is used to adapt the application to its environment in several ways.

The environment can also be passed as a command-line argument when the application is launched, but this requires us to modify Program.cs by adding a ConfigureHostConfiguration as shown below:

Get hands-on with 1200+ tech skills courses.