Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Environment variable in .NET Core Console Application from App.config

We have a .NET Core console application.

static void Main(string[] args)
{
    var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
    var builder = new ConfigurationBuilder()
        .AddJsonFile($"appsettings.json", true, true)
        .AddJsonFile($"appsettings.{environmentName}.json", true, true)
        .AddEnvironmentVariables();
    var configuration = builder.Build();
}

environmentName is always null. How to set ASPNETCORE_ENVIRONMENT in App.config file ?

like image 297
George Avatar asked Dec 06 '25 09:12

George


2 Answers

The OP specified that it's a console app. Starting from .NET Core 3.0, you will have to use DOTNET_ENVIRONMENT instead of ASPNETCORE_ENVIRONMENT for console apps. For example, the launchsettings.json will be this for Development environment:

"ConsoleApplication - Development": {
  "commandName": "Project",
  "environmentVariables": {
    "DOTNET_ENVIRONMENT": "Development"
  }
}

If you use ASPNETCORE_ENVIRONMENT, your console host will default to production environment.

Even though console apps have no launchsettings.json file in the Properties folder, as soon as you change a property in the console project's properties window, visual studio will automatically create a Properties folder and add a launchsettings.json file.

like image 188
Stack Undefined Avatar answered Dec 08 '25 21:12

Stack Undefined


You need to set the environment variable ASPNETCORE_ENVIRONMENT first before you run your application or use a default value if environment variable ASPNETCORE_ENVIRONMENT is null.

The environment variable ASPNETCORE_ENVIRONMENT has the default value Production in a aspnet-core application, because this is ensured by runtime when variable is not set.

But you have a dotnet application (console) and the variable is not initialized by default.

WINDOWS

C:\> set ASPNETCORE_ENVIRONMENT=Development
C:\> dotnet run ...

UNIX

$ export ASPNETCORE_ENVIRONMENT=Development
$ dotnet run ...
like image 20
Jehof Avatar answered Dec 08 '25 22:12

Jehof