Home > Back-end >  .NET Core Console app on Linux env var NETCORE_ENVIRONMENT - necessary?
.NET Core Console app on Linux env var NETCORE_ENVIRONMENT - necessary?

Time:11-24

Does environment variable NETCORE_ENVIRONMENT=Production mean anything when running a console app ?

In asp.net core there is ASPNETCORE_ENVIRONMENT=Production - which (as far as I know) changes the app to use appsettings.Production.json.

Does NETCORE_ENVIRONMENT exists at all and whats the effect of using it?

(I found it in my scripts when I installed 5.0 app almost a year ago, now I cant find any reference of it on Google)

CodePudding user response:

TL;DR DOTNET_ENVIRONMENT is used by the HostBuilder in console apps in .NET 5 & 6 (and maybe as early as 3.x). Beyond that it's just a common environment variable you can also use to determine the environment in case you wanted to do something like:

if (Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") == "Development")
{
    builder.AddUserSecrets<Program>();
}

I believe in .NET 5 & 6 ASPNETCORE_ENVIRONMENT and DOTNET_ENVIRONMENT are the meaningful environment variables. If neither are set, it defaults to Production. When run from ASP.NET Core the WebApplication.CreateBuilder will prefer ASPNETCORE_ENVIRONMENT if they both exist.

One further side note, I don't believe any values are set by default. I just checked my local Ubuntu server that has a fresh .NET 6 install on it and those environment variables were not created by the installer.

The following uses HostBuilder and the HostingEnvironment should reflect the value from DOTNET_ENVIRONMENT. It still felt unintuitive because I had to add the prefix: "DOTNET_" part.

class Program
{
    static void Main(string[] args)
    {
        var builder = new HostBuilder();

        builder.ConfigureHostConfiguration(config =>
        {
            config.AddEnvironmentVariables(prefix: "DOTNET_");
        });


        builder.ConfigureAppConfiguration((context, config) =>
        {
            Console.WriteLine($"HostBuilder Environment in ConfigureAppConfiguration: {context.HostingEnvironment.EnvironmentName}");
        })
        .UseDefaultServiceProvider((context, options) =>
        {
            Console.WriteLine($"HostBuilder Environment in UseDefaultServiceProvider: {context.HostingEnvironment.EnvironmentName}");
        });

        builder.Build();
    }
}

Related:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-6.0

  • Related