.NET Core environment variable returns null
Asked Answered
F

2

27

I have a .NET Core console application. I'm trying to retrieve the environment variable using the below code.

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

However, the variable "environment" always return null. I set the environment variable "ASPNETCORE_ENVIRONMENT" through

Control Panel -> System Properties -> Environment Variables -> System Variables

I also tried setting the environment variable using the command set ASPNETCORE_ENVIRONMENT=development, but that also did not work. When I debug the code (F5) in Visual Studio, the variable always return null. I have made sure that there aren't any spaces where I set the variable, or in my code where I read it. Is there anything I'm missing?

Federal answered 29/8, 2019 at 15:32 Comment(3)
qwe wrote an Answer saying "Restart VS"Aseptic
I had extra space on "ASPNETCORE_ENVIRONMENT" (i setup env var inside vs) now its working fineSwanky
Restarting VS worked for meRepentance
F
25

I think setting the environment variable would only work if you started your console application via dotnet run:

When the ASPNETCORE_ENVIRONMENT environment variable is set globally, it takes effect for dotnet run in any command window opened after the value is set.

From: Use multiple environments in ASP.NET Core


Try setting it it your Debug properties.

Right click your project in Visual Studio and select PropertiesDebug.

Set the environment variable as shown in the image below.

Enter image description here

Federicofedirko answered 29/8, 2019 at 15:36 Comment(2)
Thanks. That works. But, why is it not reading from System Properties - > Environment Variables?Federal
I think that would only work for app that were started using "dotnet run" and not when started using Visual Studio. From the documentation "When the ASPNETCORE_ENVIRONMENT environment variable is set globally, it takes effect for dotnet run in any command window opened after the value is set."Federicofedirko
V
19

It works perfectly fine for me even when you start application using Visual Studio. You just have to keep in mind that VS should be restarted after any updates to environment variables (they are not updated on the fly).

Velocity answered 31/10, 2022 at 9:35 Comment(2)
but... why is like that?Antabuse
The "restarting Visual Studio" did the trick for meGlede

© 2022 - 2024 — McMap. All rights reserved.