Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment variables configuration in .NET Core

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>()?

like image 290
Vladislav Qulin Avatar asked Sep 04 '17 13:09

Vladislav Qulin


People also ask

What are environment variables in C#?

The GetEnvironmentVariable(String) method retrieves an environment variable from the environment block of the current process only. It is equivalent to calling the GetEnvironmentVariable(String, EnvironmentVariableTarget) method with a target value of EnvironmentVariableTarget.

How is ASPNETCORE_ENVIRONMENT set?

To set the ASPNETCORE_ENVIRONMENT environment variable in Windows: Command line - setx ASPNETCORE_ENVIRONMENT "Development" PowerShell - $Env:ASPNETCORE_ENVIRONMENT = "Development"

What is config file in .NET Core?

Application configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources: Settings files, such as appsettings. json.


1 Answers

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

like image 169
Daniel Avatar answered Oct 06 '22 10:10

Daniel