Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.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.