Maxim Tkachenko
Maxim Tkachenko

Reputation: 5808

ASP.NET Core: AddEnvironmentVariables doesn't load variables

I have an asp.net core application (.NET Core 2.1). There is a code in ConfigureServices method in Startup class:

Configuration = new ConfigurationBuilder()
    .SetBasePath(_hostingEnvironment.ContentRootPath)
    .AddJsonFile("appsettings.json", false, true)
    .AddJsonFile($"appsettings.{_hostingEnvironment.EnvironmentName}.json", false, true)
    .AddEnvironmentVariables("MyApp:")
    .Build(); 

Also I set system environment variable MyApp:DumpFolder to override DumpFolder setting in appsettings.json. And here I faced with strange behavior:

  1. If I run the application from visual studio with F5 - it can't see my system environment variable
  2. If I build and run it from bin/Debug folder with dotnet MyApp.dll - it loads variables properly.

I inspected asp.net core and see it uses Environment.GetEnvironmentVariables() method which by default (without specified EnvironmentVariableTarget) retreives variables from current process. I don't understand why variables aren't loaded when I run the application from visual studio?

Upvotes: 17

Views: 20051

Answers (3)

Mikael Lundin
Mikael Lundin

Reputation: 289

I had the same problem running Docker Orchestrator with Docker Compose in Visual Studio 2019. I changed my environment variables to all uppercase and they were recognized by dotnet core.

It worked with lowercase in Docker and Docker Compose outside of Visual Studio, but in Visual Studio I had to upper case my environment variables.

Upvotes: 2

3xGuy
3xGuy

Reputation: 2559

I know this is a bit late, but my issue was that I hadn't installed the Nuget Package Microsoft.Extensions.Configuration.EnvironmentVariables.

Upvotes: 17

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30625

Restart your Visual Studio.

You probably just declared your Environment Variables hence Visual Studio does not see them.

Upvotes: 45

Related Questions