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.IHostingEnvironment
In your ASP.NET Core Startup class, thector
has a IHostingEnvironment
parameter. One of the properties on it is the EnvironmentName
. Along with this are a few extension methods such as IsDevelopment()
, IsStaging()
, IsProduction()
.
In the sample below, you can see if the environment is development, then I’m adding the User Secrets to the ConfigurationBuilder
.
What IHostingEnvironent.IsDevelopment()
ultimately does is checks to see if the IHostingEnvironment.EnvironmentName
is equals to Development
.
ASPNETCORE_ENVIRONMENT
How didIHostingEnvironment.EnvironmentName
get 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 Variables
You can also add additional environment variables that will be loaded whenConfigurationBuilder.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.