ASP.NET Core provides an option to control multiple environments for an Application. The Professional or enterprise application will have multiple environments or stages before deploying the application to the production or actual users. Multiple environments like development, staging, and production environment. The environment variable indicates the runtime environment in which an application is running currently.
ASP.NET Core apps utilize an environment variable is called
ASPNETCORE_ENVIRONMENT to indicate the application is currently running in. You can provide any value to this variable as per your requirement but normally Development, Staging, or Production environment values can be used.
The environment name is case insensitive. For example, if you set the variable to
DEVELOPMENT then the final result will be the same.
How do I set an environment variable in ASP.NET Core apps?
In Visual Studio, the environment value will be present in your project's Debug profiles, as shown below,
Right Click Your Project (e.g., ASPNETCoreApp) > Properties.
In the properties page, Click on Debug tab and you can see the environment variable as shown below,
When you change the Environment variables and the changes will be updated in the launchSettings.json file under the "Properties" folder, as shown below.
If you want you can change the Environment variables directly in the launchSettings.json file and will be reflected in the above list (Debug tab).
How do I add a new Environment variable?
Navigate to Debug tab > Click Add > Add Name and Value (shown below). For example, I have added Name as
ASPNERCORE_ENV_STAGING and Value as
The newly added Environment variable is also updated in the launchSettings.json file, as shown below.
How do I access the Environment variable in Runtime?
IHostingEnvironment service provides EnvironmentName property which contains the value of
ASPNETCORE_ENVIRONMENT a variable. You can access Environment Value using this property in runtime. Also you can use ASP.NET Core extension methods to check the environments such as IsDevelopment(), IsStating(), IsEnvironment() and IsProduction().
If you want to check a particular environment, then you can use
IsEnvironment as shown below,