Sabari M Sabari M
Updated date Dec 13, 2020
In this article, we will learn What is ASP.NET Core Environment Variables and Configurations and how to set and access environment variables and configuration steps.

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 or development or 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 STAGING.

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?

The 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 EnvironmentName or IsEnvironment as shown below,

ABOUT THE AUTHOR

Sabari M
Sabari M
Software Professional, India

IT professional with 14+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (2)