Sponsorship is available! If you’d like to sponsor CodeOpinion.com and have your product or service advertised exclusively (no AdSense) on every post, contact me.In my last post, I covered how to handle sensitive configuration data by using User Secrets while working in development or on your local machine. The next step is how to use environment variables in ASP.NET Core once you deploy to production (eg Azure App Service)? If you have any questions, please follow me on Twitter.
IHostingEnvironmentIn your ASP.NET Core Startup class, the
IHostingEnvironmentparameter. One of the properties on it is the
EnvironmentName. Along with this are a few extension methods such as
IsProduction(). In the sample below, you can see if the environment is development, then I’m adding the User Secrets to the
IHostingEnvironent.IsDevelopment()ultimately does is checks to see if the
IHostingEnvironment.EnvironmentNameis equals to
IHostingEnvironment.EnvironmentNameget set to
Development? If you are using Visual Studio you can access this in the in the project properties. If you are outside of Visual Studio, you can manage it by editing the
launchSettings.json. This is what a sample looks like.
Environment VariablesYou 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.