1

I have the following code in my Program.cs:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)            
        .ConfigureAppConfiguration(b => b
            .AddEnvironmentVariables()
            .AddMyCustomConfiguration(o => o.UseSqlServer(
                Environment.GetEnvironmentVariable("ConnectionStrings:MyDatabase"))))                
        .UseStartup<Startup>();

My appsettings.json looks like this:

{
  "ConnectionStrings": {
    "MyDatabase": "connectionstring"
  }
}

However, Environment.GetEnvironmentVariable("ConnectionStrings:MyDatabase") is returning null. I was under the impression that AddEnvironmentVariables would load the necassary variables. Is this not the case / how can I get this to load the connection string?

3 Answers3

1

For getting ConnectionStrings from appsettings.json, you should use GetConnectionString instead of reading environment.

Try something like below:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)            
    .ConfigureAppConfiguration(b => {
            b.AddEnvironmentVariables();
            var connectionString = b.Build().GetConnectionString("MyDatabase");
            .AddMyCustomConfiguration(o => o.UseSqlServer(connectionString));
    })              
    .UseStartup<Startup>();
Edward
  • 28,296
  • 11
  • 76
  • 121
0

See this example

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
  .ConfigureAppConfiguration((hostingContext, config) =>
  {
    var env = hostingContext.HostingEnvironment;

    config.AddJsonFile("application.json", optional: false, reloadOnChange: true);
    config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
    config.AddEnvironmentVariables("ASPNETCORE_");
    config.AddCommandLine(args);
  })
  .UseStartup<Startup>();

here you have the link to the article https://www.johanohlin.com/blog/configuration-providers-in-aspnet-core/

Pedro Brito
  • 263
  • 1
  • 9
  • This doesn't make any difference. I've tried various combinations on the approach, but no luck. Obviously AddEnvironmentVariables("ASPNETCORE_") is no good to me, so I just load them all –  Sep 12 '19 at 12:11
0

You've put your settings into JSON config, not into env var(s). This is why GetEnvironmentVariable() returns nothing. And ASP.Net Core is not intended to export your config to env vars unless you did that explicitly (let say, via SetEnvironmentVariable() or an equivalent).

If you actually intend to just read a connection string value, take a look on this topc How to read connection string in .NET Core?

Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42