0

I deploy a .NET 6 console app to multiple environments (Dev, Staging, Production).

In ASP.NET hosted applications, I can set the ASPNETCORE_ENVIRONMENT value, so that an additional appsettings.{Staging}.json file is read in. Is there an equivalent way I can specify the environment from the command line for the console app? I do not want to modify the system-wide environment variables on the host machines but am considering using a batch file.

I want to do something like

dotnet mydotnetconsoleapp.dll --environment=Staging

then it should read in appsettings.Staging.json I read that --environment should work but I think am doing something wrong.

I am on Windows.

Zahir J
  • 1,117
  • 9
  • 20
  • You can still start the process with `ASPNETCORE_ENVIRONMENT` environment variable. They just changed the name. e.g. `ASPNETCORE_ENVIRONMENT=Staging dotnet run`. Refer to the docs here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-7.0#environments – nbokmans Mar 14 '23 at 10:53
  • You can already mix multiple configuration sources out of the box. There's nothing special about appsettings.json, that's just the default name of a JSON settings file. By default, Environment variables and command-line arguments are merged to provide the configuration settings – Panagiotis Kanavos Mar 14 '23 at 10:55
  • Does this answer your question? [.NET Core 3.1 Worker Service - set EnvironmentName on publish](https://stackoverflow.com/questions/60741863/net-core-3-1-worker-service-set-environmentname-on-publish) It contains both an option that you can use in your batch script, or an alternative using a dedicate `hostsettings.json` file to designate the environment. – Alex AIT Mar 14 '23 at 13:08

1 Answers1

1

If you are using the Generic Host, then yes.

https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host#host-configuration

A simple console app, on its own, won't honor a command-line argument unless you write something to parse it.

If your code is going to run in a Linux environment, I'd suggest the environment variable approach and a launch command like MYPREFIX_ENVIRONMENT=development dotnet mydotnetconsoleapp.dll

Stand__Sure
  • 253
  • 1
  • 13
  • I can't pass in command line arguments as there some complex configuration objects used. I want to specify the Environment through a command line or other switch on Windows. – Zahir J Mar 14 '23 at 12:58