Most of the time there are multiple developers working on the same project. But we don't want to have the same settings in our appSettings.json.
Some developers use localdb, other SQL Express or a connectionstring to the Cloud. API keys or endpoints may differ, paths and domains etc. A lot of things can be different.
When deploying to our test, staging and production environments on Azure, we also need different settings.
With the previous version of ASP.Net we used the excellent NConfig. But with ASP.Net Core 1.0 it became much simpeler to get configuration values from different sources.
Let's dive right into the source code.
So what does this do?
First we try to find the environment vairable NCONFIG_ALIAS. This is used when deploying to Azure and load Azure specific configuration. We set the environment variable in Azure to "azure-production".
If the NCONFIG_ALIAS is not available, we try to find the COMPUTERNAME.
We now have a configAlias with the value of NCONFIG_ALIAS or our COMPUTERNAME.
Next thing is to call the configuration builder and load our configuration.
Our main and default configuration is in appsettings.json.
After that we load appsettings..json.
The environmentName on a local machine is Development and will be Production when deploying. Think of this as the old Web.Debug.config and Web.Release.config.
After that we load Configuration\appsettings..json. So this will be appsettings.MyComputerName.json.
In appsettings.MyComputerName.json I can put all my local configuration overrides. Most of the time we put this file into source control, but you can choose not to do that.
Last thing is to call AddEnvironmentVariables(). This will allow you to override individual configuration values through the environment variables. That's useful when deploying to Azure and you want to override a connnectionstring.
Secrets in the Secret Store
Passwords and other sensitive data should never be stored in code or checked into source control. During development you can use thesecret store.
When your app is running in production, there's no secret store available. You can then provide the secret values using Environment Variables which you can set easily in the Azure Portal.