1

I have a .NET 6 Web API application and I have define one key in "appsettings.json" file in a below way,

{
 "UID": "myUid"
}

Now I want to read the "UID" key like as environment variable like,

 var x = Environment.GetEnvironmentVariable("UID");

It's give me "null" result. What fix is required here?

I know I can put the key in launsettings.json and it will work, but I want to put only in appsettings.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
user584018
  • 10,186
  • 15
  • 74
  • 160

1 Answers1

3

ASP.NET Core allows hierarchical set up for setting sources. By default WebApplicationBuilder provides configuration for the app in the following order, from highest to lowest priority:

  • Command-line arguments using the Command-line configuration provider.
  • Non-prefixed environment variables using the Non-prefixed environment variables configuration provider.
  • User secrets when the app runs in the Development environment.
  • appsettings.{Environment}.json using the JSON configuration provider. For example, appsettings.Production.json and appsettings.Development.json.
  • appsettings.json using the JSON configuration provider.
  • A fallback to the host configuration (read more)

For development environments you can use launchSettings.json to set up environment variables. So for local development environment you can use it or just provide required config via appsettings.Development.json or set them via CLI parameters.

Personally I tend to exclude launchSettings.json from version control monitoring and use it for user specific environment settings (i.e. settings which are highly likely to differ for different developers) and use appsettings.Development.json for everything else.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 1
    For VS Code users, I would like to add to this marvelous answer that environment variables are set in the `launch.json` file in the `.vscode` folder. – José Ramírez Oct 27 '22 at 15:20