The confusion of ASP.NET Configuration with environment variables

What comes after what in config?

Georgi Parlakov
2 min readSep 13, 2018

--

tl;dr; Env variables with ASPNETCORE_ prefix get overridden by your appSettings.json and then by appSettings.Development.json because these are meant to be host level — and not app level. (That’s when using the
WebHost.CreateDefaultBuilder). If you want to override appSettings.json you can use User secrets or non-prefixed environment variables.

Below we’ll see why config is a bit confusing then give some concise guidance as to what comes after what in configuring ASP.NET Core apps

The confusion (for me) comes from reading the article where it’s stated that not all environment variables get “loaded” for optimization purposes. And prefixed ones do get loaded — that’s why I decided to use the prefix. And the prefixed env variable gets overridden.

Indeed if you have say a connection string inside the appSettings.json:

And then add an environment variable of ASPNETCORE_ConnectionStrings__MyConnection = myDevDataSource and try to load that connection string you’ll get the one from appSettings.json.
Notice the __ in the environment variable — that’s a platform — safe way to indicate nested configuration i.e. that gets loaded in config as ConnectionStrings:MyConnection

And if you create an environment variable (and restart VS in order to reload those) ConnectionStrings__MyConnection = myDevDataSource and try loading that — you’ll get your environment variable one — it gets precedence over the appSettings.json.

So the order of precedence is (the next item will overwrite the previous):
* Host config (with ASPNETCORE_ )
* appSettings.json
* appSettings.Development.json
* User secrets (I love this — see below)
* environment variables
* cmd-line args
All this is true if you are using the CreateDefaultBuilder. If rolling your own — you decide the order.

From https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host?view=aspnetcore-2.1#set-up-a-host

About the User secrets — these are easily accessible from Visual Studio. They are simply a json file hidden in your user’s folder. And get applied on a per-project base by the UserSecretsId. More details here.

--

--