Azure and .NET nested JSON sections. Did you know?

2022, Feb 01

.NET Core (and ASP.NET Core) supports (hierarchical configuration data)1, which is represented by nesting JSON sections.

Let's look at this JSON configuration file:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  },
  "SecretSettings": {
    "SqlConnectionString": "Sql connection string",
    "BlobConnectionString": "Blob connection string"
  }
}

We have variables nested within sections of the JSON. i.e.: SecretSettings:SqlConnectionString.

When .NET reads this information, it uses the Configuration Providers hooked up as middlewares, i.e.:

var config = new ConfigurationBuilder()
  .SetBasePath(appDirectory)
  .AddJsonFile(Path.Combine(appDirectory, "settings.json"), optional: true, reloadOnChange: true) // config provider
  .AddEnvironmentVariables() // config provider
  .Build();

The Configuration API then reads the hierarchical configuration data by flattening it with the use of a delimiter in the configuration keys. The delimiters can be either : (colon) or __ (double underscore).

Did you know that depending on the underlying platform you need to specify the correct delimiter?

If you are on a Linux app service or container, you must use __, but if you are on the Windows platform you can use either __ or :. This is used as environment variables loaded when running apps.

Microsoft says the same in this article

In a default Linux app service or a custom Linux container, any nested JSON key structure in the app setting name like ApplicationInsights:InstrumentationKey needs to be configured in App Service as ApplicationInsights__InstrumentationKey for the key name. In other words, any : should be replaced by __ (double underscore).