Environment variable in ASP .NET Core
.NET Core .NET

Environment variable in ASP .NET Core

Mishel Shaji
Mishel Shaji

Developing an application can be divided into several stages including Development, Staging, and Production. In ASP .NET Core, you can manage the behaviour of the application in these stages with the help of an Environment variable.

An Environment variable indicates the current phase of the application. Normally, it can be Development, Staging, or Production. You can also use your own phases.

Environment variable

In ASP .NET Core, the ASPNETCORE_ENVIRONMENT variable holds the phase of your application.

In Visual Studio, go to Solution Explorer -> Right click on the project -> Properties. In the window that appears, navigate to the Debug tab. This will display the environment variables of your application.

Environment variables in ASP .NET Core

You can also change this value from launchSettings.json under Properties.

{
   "iisSettings": {
     "windowsAuthentication": false, 
     "anonymousAuthentication": true, 
     "iisExpress": {
       "applicationUrl": "http://localhost:4439",
       "sslPort": 44321
     }
   },
   "profiles": {
     "IIS Express": {
       "commandName": "IISExpress",
       "launchBrowser": true,
       "environmentVariables": {
         "ASPNETCORE_ENVIRONMENT": "Development"
       }
     },
     "ASPCoreWeb": {
       "commandName": "Project",
       "launchBrowser": true,
       "applicationUrl": "https://localhost:5001;http://localhost:5000",
       "environmentVariables": {
         "ASPNETCORE_ENVIRONMENT": "Development"
       }
     }
   }
 }

Accessing environment variable

ASP .NET Core reads the value of Environment variable at app startup and stores it in the IHostingEnvironment.EnvironmentName. If ASPNETCORE_ENVIRONMENT is not set, it will be considered as Production.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    if (env.IsProduction()
    {
        app.UseExceptionHandler("/Error"); 
    }
    app.UseStaticFiles();
    app.UseMvc(); 
}

Environment tag helper

The Environment tag helper can be used to display or hide specific portions of the markup in the code.

To understand how this works, add the following code to Index.cshtml (under Pages) and run the application.

<environment include="Development">
    <h1>Development environment</h1>
</environment>
<environment exclude="Development">
    <h1>Development. Will not be displayed.</h1>
</environment>
<environment include="Staging,Development">
    <h1>Staging or Development.</h1>
</environment>