Environment variables configuration in .NET Core

Vladislav Qulin picture Vladislav Qulin · Sep 4, 2017 · Viewed 8.7k times · Source

I'm using the .NET Core 1.1 in my API and am struggling with a problem:

  1. I need to have two levels of configurations: appsettings.json and environment variables.
  2. I want to use the DI for my configurations via IOptions.
  3. I need environment variables to override appsettings.json values.

So I do it like this so far:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables();
}

public IServiceProvider ConfigureServices(IServiceCollection services)
{
     // Something here
     services.Configure<ConnectionConfiguration>(options =>
            Configuration.GetSection("ConnectionStrings").Bind(options));
     // Something there
}

With my appsettings.json composed like this

{
    "ConnectionStrings": {
        "ElasticSearchUrl": "http://localhost:4200",
        "ElasticSearchIndexName": "myindex",
        "PgSqlConnectionString": "blablabla"
    }
}

I get all the configurations mapped to my class ConnectionConfiguration.cs. But I cannot get the environment variables to be mapped as well. I tried the names like: ConnectionStrings:ElasticSearchUrl, ElasticSearchUrl, even tried specifying the prefix to .AddEnvironmentVariables("ConnectionStrings") without any result.

How should I name the environment variables so it can be mapped with services.Configure<TConfiguration>()?

Answer

Daniel picture Daniel · Jul 8, 2020

The : separator doesn't work with environment variable hierarchical keys on all platforms. __, the double underscore, is supported by all platforms and it is automatically replaced by a :

Try to name the environment variable like so ConnectionStrings__ElasticSearchUrl

Source