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)?
In your ASP.NET Core Startup class, the
ctor has a
IHostingEnvironment parameter. One of the properties on it is the
EnvironmentName. Along with this are a few extension methods such as
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.EnvironmentName is equals to
IHostingEnvironment.EnvironmentName get set to
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.
You can also add additional environment variables that will be loaded when
ConfigurationBuilder.AddEnvironmentVariables() is called in
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.
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.
Always enjoy hear your feedback. Please let me know on twitter or in the comments.