Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core environment variable returns null

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?

like image 387
Thomas Avatar asked Aug 29 '19 15:08

Thomas


People also ask

How do I check environment variables in .NET core?

Open project properties by right clicking on the project in the solution explorer and select Properties. This will open properties page. Click on Debug tab and you will see Environment Variables as shown below. You may change the value as per your need.

How do I set environment GetEnvironmentVariable?

GetEnvironmentVariable(envVar, EnvironmentVariableTarget. Machine) Console. WriteLine($" {envVar}: {value}") Next Console. WriteLine() ' Delete the environment variable for each target.

How do you set an environment variable in the net core console app?

With all these packages installed, I could initialize the ConfigurationBuilder with a subset of the default ASP.NET Core setup: var environment = Environment. GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); var builder = new ConfigurationBuilder() . AddJsonFile($"appsettings.

How do I read an environment variable in PowerShell?

Environment variables in PowerShell are stored as PS drive (Env: ). To retrieve all the environment variables stored in the OS you can use the below command. You can also use dir env: command to retrieve all environment variables and values.


1 Answers

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

like image 188
Paul Lorica Avatar answered Sep 21 '22 01:09

Paul Lorica