Environment Variables in ASP.NET Core
Once you deploy your project to the production for example Azure App Service we need take care of Environment Variables and we are gonna see here how to that.
IHostingEnvironment
In your ASP.NET Core Startup class, the constructor has a IHostingEnvironment parameter. And EnvironmentName is its one of the properties. There even exits few Extension methods such as IsDevelopment(), IsStaging(), IsProduction() etc aling with the EnvironmentName..
In the sample below, you can see if the environment is development, then I’m adding the User Secrets to the ConfigurationBuilder.
In the above snapshot, What env.EnvironmentName does is that it checks whether IHostingEnvironment. Environment is equals to Development or not.
If you are outside of Visual Studio, you can manage it by editing the launchSettings.json.This is what a sample looks like.
Environment Variables
You can also add additional environment variables that will be loaded when ConfigurationBuilder.AddEnvironmentVariables() is called in Startup.
In my above example, only under development are user secrets loaded. This is done after environemnt variables are loaded. This means that the user secrets override any environment variables I’ve set.
Azure AppService
Once you are ready to deploy to azure, you may want to set your environment as well as other environment variables that you need which will be used instead of user secrets. You can do this in your App Service under Application Settings.