Setting up Environment Variables in .NET Core 3.1

What is Environment Variable?

Typically, in real-world application development, there are multiple stages where an application is tested before it gets available to the real users. These phases are known as development, staging, and production as per convention. The most common requirement is to set up a different database connection string for a different environment. Environment variable used to indicate the runtime environment in which the application is currently running.

ASP.NET Core uses an environment variable known as ASPNETCORE_ENVIRONMENT to indicate a runtime environment. The value of this variable can be anything based on the application phase. Typically the value of this variable can be Development, Staging, Production OR CustomValue. These values in a case insensitive in Windows and Mac Os but it’s case sensitive in Linux.

How to setup?

Environment varaible in project properties

In Visual Studio, we can set ASPNETCORE_ENVIRONMENT in the debug tab of project properties. Open project properties by right-clicking on the project in the solution explorer and select Properties

Setup different profiles

Environment Variables 2
Environment profiles

As you can see in Image 2, there are 3 JSON files.

  1. appSettings.Development.json (For Development environment)
  2. appSettings.json (Default and we used for Production environment)
  3. appSettings.LocalStaging.json (For Local IIS Express environment)

We can get the value of the environment variable in our code in order to execute some additional code depending on the environment. The IHostingEnvironment includes EnvironmentName property that contains the value of ASPNETCORE_ENVIRONMENT variable. ASP.NET Core have extension methods to check environment such as IsDevelopment(), IsStaging(), IsEnvironment() and IsProduction().

The IWebHostEnvironment service is provided by ASP.NET Core 3.1 hosting layer and can be used anywhere in your application via Dependency Injection. The following example shows how we can check the environment variable in Configure method of Startup class.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsEnvironment("Development"))
    {
        // code to be executed in development environment 
    }

    if (env.IsDevelopment())
    {
        // code to be executed in development environment 
    }

    if (env.IsStaging())
    {
        // code to be executed in staging environment 
    }

    if (env.IsProduction())
    {
        // code to be executed in production environment 
    }
} 

Last but not least, you can run your application by selecting profile shown in Image 3

Run environment profile
Run environment profile

How to publish a project for a specific environment

dotnet publish /p:Configuration=Release /p:EnvironmentName=LocalStaging

Hire us for .NET Development

One thought on “Setting up Environment Variables in .NET Core 3.1

Comments are closed.