(C# ASP.NET Core) Environments in ASP.NET Core

This tutorial explains about the various environments like Development, Staging and Production. We also explain how to set them by various methods and how to conditionally check for environments and perform settings.
(Rev. 19-Mar-2024)

Categories | About |     |  

Parveen,

The Terminology of Environments

Let us first go through the terminology of environments in software development.

You may have already heard of three broad stages of development - Production, Staging and Development. In some literature you may have heard of alternate but similar terms like beta, alpha, etc., also.

During the first stage, an application is run with settings for easier debugging and logging. There is a lot of redundant code that helps a developer examine the state of various variables. These settings are collectively called the Development environment.

An app running in the Production environment is opened for the use of end customers. The environment settings are such that the debugging and logging code is either removed, or replaced by NOP - no operation statements. Efficiency of execution is the main objective here.

The Staging environment has all the settings of the Production environment, but the app is run on the development computer. It is like a final rehearsal.

Video Explanation

Please watch the following youtube video:

Why do we need different Environments in an ASP.NET Core Application

Let us give various reasons for: why do we need different Environments in an ASP.NET Core Application?

One reason is that an application under development needs detailed logs and exception messages, but the case is just the opposite if the same app runs under production.

Another example is that caching of images and static files can be disabled during development because of frequent changes. But it must be enabled for an app in production. This can help save bandwidth for download of images, etc.,

A yet another example is that during development it is easier to debug well-formatted CSS and JS files. However, the CSS and JS scripts can be served in minified form when the app is running under a production environment.

How to set Environment in an ASP.NET Core Application

Method 1: Set an environment variable called DOTNET_ENVIRONMENT on the server machine.

Method 2: Set the environment variable called ASPNET_ENVIRONMENT on the machine. It takes precedence over DOTNET_ENVIRONMENT. This alternative has probably been provided so that an application can over-ride the environment setting.

The environment variable called ASPNET_ENVIRONMENT is usually set through the launchSettings.json file in visual studio. It takes precedence over the values set in the globally in the system.

Let us open visual studio to examine the launchSettings file. This file is located in the solution explorer in a folder called Properties. We suggest that you download the attached file and open it in visual studio 2022 or later.

We shall discuss the details of this file in a later tutorial, but for now we can see two debug profiles in this file. We shall talk about these profiles later, but you can see these profiles set an environment variable ASPNETCORE_ENVIRONMENT to Development.

"profiles": {

    "MyRazorApp": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localho...,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }

This file is a sort of temporary file for use during development - it is not used by the actual hosting server. It is never deployed.

If neither DOTNET_ENVIRONMENT, nor ASPNET_ENVIRONMENT is set, then the default environment is Production.

Method 3: There is a third method for setting the environment through the CreateBuilder method in the program.cs file

Let us open the Program.cs file. This file has been generated through Visual Studio 2022 running dotnet 6. The main function is implied in newer versions of C#. This code is the code of the entry point Main function.

We can set the environment by passing WebApplicationOptions to an overload of the CreateBuilder method.


// Visual Studio 2022 .NET 6 
// extract of the Program.cs file 

//~ reads ASPNETCORE_ENVIRONMENT variable
// from launchsettings.json 
var builder = WebApplication.CreateBuilder(

    new WebApplicationOptions() 
    { 
      EnvironmentName = 
        Microsoft.Extensions.Hosting.Environments.Development 
    }

  );

Conditional Configuration in an ASP.NET Core Application

ASP.NET Core allows us to configure the app behavior on the basis of Production, Staging and Development environments.

IsDevelopment, IsProduction and IsStaging are three built-in methods for conditional check of the current environment setting. This code shows how to test for an environment that is any other than Development, and apply the relevant settings


// Visual Studio 2022 .NET 6 
// extract of the Program.cs file 

//~ only relevant code shown
var app = builder.Build();

// Configure the HTTP request pipeline. 
if (!app.Environment.IsDevelopment())
{
  app.UseHsts();
}

//~ remaining code not shown 
// . . .  
}

There is a general purpose method that allows us to test for any custom environment, say, of a name such as MyCustom.

if (app.Environment.IsEnvironment("MyCustom"))
  {
    app.UseExceptionHandler("/Custom");
  }
  else
  {
    app.UseExceptionHandler("/Error");
  }

Conditional Markup in Razor Pages

ASP.NET Core makes available a tag helper called environment that allows us to render a markup on the basis of the current environment.

Let us have a look at our index.cshtml file. It contains two environment tags.

The first tag uses an include atribute to specify that the markup will render only if the environment is Production or Staging.

The second tag renders only if the environment is any other except Production


// index.cshtml razor page 

@page

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<environment include="Staging,Production">
  
  <p>
    include="Staging,Production"
  </p>

  <p>
    This markup appears only if the environment
    is Staging or Production
  </p>
</environment>

<environment exclude="Production">
  
  <p>
    exclude="Production"
  </p>

  <p>
    This markup doesn't appear in Production.
    It appears during staging, development, and
    any other.
  </p>

</environment>

Running the App

Let us run the app. The current environment is Development.

We verify that the second tag appears but not the first one.

Next let us open the program.cs file.

Change the environment to Production.

Run the app now!

We verify that the first environment tag renders now, as expected.

This is how we can work with environment settings. Thankyou!


This Blog Post/Article "(C# ASP.NET Core) Environments in ASP.NET Core" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.