ASPNETCORE_ENVIRONMENT is an environment variable, which ASP.NET Core uses to identify the runtime environment. ASP.NET Core configuration system uses it to load different configurations for different stages of application like Development, Staging & Production, etc. In this tutorial, we will show what is ASPNETCORE_ENVIRONMENT and how to set its value while developing the application and while hosting the application, etc.
Table of Contents
What is ASPNETCORE_ENVIRONMENT
An application moves through different stages before it reaches the end-user. Each of these stages requires different requirements and configurations. For Example, we need to load different connection strings for development & Production. Similarly, we need to configure features like logging, minification, exception handling differently for different stages of the application.
To Load different configurations for different stages, ASP.NET Core needs to identify the stage or environment, in which the application is running. This is where it uses the ASPNETCORE_ENVIRONMENT
environment variable.
Loading ASPNETCORE_ENVIRONMENT
The ASP.NET Core Configuration system automatically loads the ASPNETCORE_ENVIRONMENT variable during the application startup. It does so very early in the application (even before the creation of the host).
Open the program.cs and you will see the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } |
The purpose of the CreateHostBuilder
is to build the host. To do that it invokes the CreateDefaultBuilder
method. The following is the source code of CreateDefaultBuilder
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | public static IWebHostBuilder CreateDefaultBuilder(string[] args) { var builder = new WebHostBuilder(); if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey))) { builder.UseContentRoot(Directory.GetCurrentDirectory()); } if (args != null) { builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build()); } builder.ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); if (env.IsDevelopment()) { var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName)); if (appAssembly != null) { config.AddUserSecrets(appAssembly, optional: true); } } config.AddEnvironmentVariables(); if (args != null) { config.AddCommandLine(args); } }) ... ... ... return builder; } |
The first line of code creates a WebHostBuilder
.
1 2 3 4 | var builder = new WebHostBuilder(); |
The source code of the WebHostBuilder
. The constructer method creates new HostingEnvironment
. The next line loads the environment variables, which starts with ASPNETCORE_
.,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public WebHostBuilder() { _hostingEnvironment = new HostingEnvironment(); _config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build(); if (string.IsNullOrEmpty(GetSetting(WebHostDefaults.EnvironmentKey))) { // Try adding legacy environment keys, never remove these. UseSetting(WebHostDefaults.EnvironmentKey, Environment.GetEnvironmentVariable("Hosting:Environment") ?? Environment.GetEnvironmentVariable("ASPNET_ENV")); } if (string.IsNullOrEmpty(GetSetting(WebHostDefaults.ServerUrlsKey))) { // Try adding legacy url key, never remove this. UseSetting(WebHostDefaults.ServerUrlsKey, Environment.GetEnvironmentVariable("ASPNETCORE_SERVER.URLS")); } _context = new WebHostBuilderContext { Configuration = _config }; } |
The CreateDefaultBuilder
method gets the value of the current environment from the HostingEnvironment
.
The further down in the CreateDefaultBuilder
method, you will see that ASP.NET core making use of the ASPNETCORE_ENVIRONMENT
to load different configurations. For Example, it loads the appsettings.development.json
if the environment is development & appsettings.production.json
, when the production.
1 2 3 4 5 6 | config .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); |
The .NET Core provides built-in support for development, staging, and production environment. We can also define our own custom environment.
Setting the ASPNETCORE_ENVIRONMENT
How we set the environment variable depends on the OS. We covered this in our tutorial on how to set the environment variable in ASP.NET Core.
Windows OS
For Windows OS, you can use the
- Command-line utility
- PowerShell
- Windows GUI Tool
Temporarily. only for the current session
1 2 3 | D:\>set ASPNETCORE_ENVIRONMENT="PRODUCTION" |
Permanent only for the current logged in user. You need to close the window and open the new window for changes to be effective
1 2 3 | D:\>setx ASPNETCORE_ENVIRONMENT="PRODUCTION" |
Same as above, but for all users (machine wise)
1 2 3 | D:\>setx ASPNETCORE_ENVIRONMENT="PRODUCTION" /m |
PowerShell
The following command creates the variable only for the current window. Changes is lost , when the window is closed.
1 2 3 | $Env:ASPNETCORE_ENVIRONMENT = "STAGING" |
The following creates the Permanent change. But you need to close and create a new window. Use the third argument to create the variable either for the current user / machine wise.
1 2 3 4 | [Environment]::SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "STAGING", "User") [Environment]::SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "STAGING", "Machine") |
Windows GUI tools
Using the GUI tool is the easiest way to create the ASPNETCORE_ENVIRONMENT variable
Go to Control Panel -> System -> Advanced System Settings -> Environment Variables. You will see the following screen. Add the Variable either the User Variable or to system variables by clicking on the new button.
Linux/ Mac
Use the export to temporarily set the Environment variable.
1 2 3 | export ASPNETCORE_ENVIRONMENT='PRODUCTION' |
To save the variable permanently you need to consider the shell that you are using. The most used shell is the bash shell. But the latest version of Mac uses the Zsh Shell.
bash shell
- login shell will load
/etc/profile
,~/.bash_profile
,~/.bash_login
,~/.profile
in the order - non-login interactive shell will load
~/.bashrc
- non-login non-interactive shell will load the configuration specified in the environment variable
$BASH_ENV
Open the shell file in an editor and add the following at the bottom
1 2 3 | export ASPNETCORE_ENVIRONMENT='PRODUCTION' |
Zsh Shell
Open /.zprofile
and add the following command at the bottom
1 2 3 | export ASPNETCORE_ENVIRONMENT='PRODUCTION' |
IIS Server
For the IIS Server use the web.config
file to set the value of ASPNETCORE_ENVIRONMENT
. Add the following under the aspNetCore
node
Use web.config
1 2 3 4 5 6 | <environmentVariables> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> |
The sample web.config
. is as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?xml version="1.0" encoding="utf-8"?> <configuration> <location path="." inheritInChildApplications="false"> <system.webServer> <handlers> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" /> </handlers> <aspNetCore processPath="dotnet" arguments=".\EnvironmentVariable.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" > <environmentVariables> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> </aspNetCore> </system.webServer> </location> </configuration> |
changes made to the web.config
directly are lost, when you run publish again.
There are three ways, you can solve this problem. Thanks to the stackoverflow.com
Modifying the project file (.CsProj) file
1 2 3 4 5 6 7 8 | <PropertyGroup Condition=" '$(Configuration)' == '' Or '$(Configuration)' == 'Debug'"> <EnvironmentName>Development</EnvironmentName> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' != '' AND '$(Configuration)' != 'Debug' "> <EnvironmentName>CustomEnvrionment</EnvironmentName> </PropertyGroup> |
Adding the EnvironmentName Property in the publish profiles
You will find the publish profile in the folder Properties/PublishProfiles/<profilename.pubxml>
.
1 2 3 4 5 | <PropertyGroup> <EnvironmentName>Development</EnvironmentName> </PropertyGroup> |
Command line options using dotnet publish
Pass the property EnvironmentName as a command-line option to the dotnet publish
command.
1 2 3 | dotnet publish -c Debug -r win-x64 /p:EnvironmentName=Development |
All the three methods will update the web.config
, when you publish the application.
Visual Studio
If you are debugging the code using the visual studio, remember that it also loads the environment variables from the launchSettings.json
. The settings from the launchSettings.json always overwrite any environment variable we define in the OS.
A typical launchsetting.json
is as below. We can add any environment variable under the node environmentVariables
. for each debug profile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | { "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:61764", "sslPort": 44369 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "KEY" : "Key from LaunchSettings.json" } }, "EnvironmentVariable": { "commandName": "Project", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "KEY" : "Key from LaunchSettings.json" }, "applicationUrl": "https://localhost:5001;http://localhost:5000" } } } |
You read more about launchSettings.json & debug Profile
Visual Studio, loads the environment variables when it starts up. Hence if you make any changes to the environment variable, your application will not read it. You have to restart the Visual Studio to reload the environment variables
Visual Studio Code
The visual studio uses the .vscode/launch.json file
for configuration. The file is as shown below. You can change the environment variable from the "env"
node.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": ".NET Core Launch (web)", "type": "coreclr", "request": "launch", "preLaunchTask": "build", "program": "${workspaceFolder}/bin/Debug/netcoreapp3.1/vscode.dll", "args": [], "cwd": "${workspaceFolder}", "stopAtEntry": false, "serverReadyAction": { "action": "openExternally", "pattern": "\\bNow listening on:\\s+(https?://\\S+)" }, "env": { "ASPNETCORE_ENVIRONMENT": "Development", "KEY" : "Key from launch.json" }, "sourceFileMap": { "/Views": "${workspaceFolder}/Views" } }, { "name": ".NET Core Attach", "type": "coreclr", "request": "attach", "processId": "${command:pickProcess}" } ] } |
dotnet run
dotnet run
command runs the application from the source code. It will pickups the environment variables from the OS. But if you make any changes to the environment variable, ensure that you close and reopen the shell
You can use the --launch-profile
flag to specify the debug profile. In such case, the environment variable from the launchSettings.json, will take precedence over those from the OS
1 2 3 | dotnet run --launch-profile="Test" |
Reading ASPNETCORE_ENVIRONMENT
Using IWebHostEnvironment
You can read the ASPNETCORE_ENVIRONMENT
by injecting the IWebHostEnvironment
in the constructor of any class.
EnvironmentName
: Read/write property used to get or set the name of the environmentIsDevelopment()
: Returns true if the EnvironmentName
is Development
IsStaging()
: True if the EnvironmentName
is Staging
IsProduction()
: Returns true if the EnvironmentName
is Production
IsEnvironment(string environmentName)
: Returns true if the passed argumentenvironmentName
matches the current EnvironmentName
1 2 3 | if (env.IsDevelopment()) { /* do something */ } |
Environment Tag Helper
We can also display the content based on the value of the environment variable using the Environment Tag Helper.
For Example
1 2 3 4 5 6 7 8 9 10 11 12 13 | <environment include="Development"> <h1>This only renders in the Development Environment</h1> </environment> <environment exclude="Development"> <h1>This content is not rendered in the Development Environments!</h1> </environment> <environment names="Development,Production"> <h1>This renders in Development and Production Environments</h1> </environment> |
Great Information. Thanks for sharing