HASSANHABIB

§ 3.1 — The Standard Team Practices

App Settings and Environment Variables

3 min read · chapter 11 of 15

A .NET app will automatically load and register appsettings.json and appsettings.{Environment}.json with the IConfiguration interface during application startup, if the files are located in the application’s root directory. This means that the key-value pairs defined in the appsettings.json file will be accessible through the IConfiguration object, allowing developers to easily access and use the configuration settings throughout their application.

It’s worth noting that in addition to the appsettings.json file, there are other configuration providers available in .NET that allow developers to load configuration settings from various sources, such as environment variables or command-line arguments. (Developers can also create their own custom configuration providers to load configuration settings from other sources if needed.)

Configuration sources are read in the order that their configuration providers are specified. Order configuration providers in code to suit the priorities for the underlying configuration sources that the app requires.

A typical sequence of configuration providers is:

  1. appsettings.json
  2. appsettings.{Environment}.json
  3. User secrets
  4. Environment variables using the Environment Variables configuration provider.
  5. Command-line arguments using the Command-line configuration provider.

Let’s look at some code samples to see how all this works.

An Example

appsettings.json

{
  "MySettings": {
    "ApiUrl": "https://api.somesite.com/",
    "ApiKey": "1ae4e397-ec3c-4ed7-8280-a17d0e2cbe78",
    "OrganisationId": "1bac6df0-cd68-4ce5-9c29-b2beb58201cd"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

With the above appsettings.json file we can then load our variables like this:

    string apiUrl = configuration["MySettings:ApiUrl"];
    string apiKey = configuration["MySettings:ApiKey"];
    string organisationId = configuration["MySettings:OrganisationId"];

Environment Variables

We can add environment variables to a web application by doing this:

var builder = WebApplication.CreateBuilder(args);
...
builder.Configuration.AddEnvironmentVariables();
...
var app = builder.Build();

or if you want to play with this in a Console App or Unit Test, you can do this:

var configurationBuilder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddEnvironmentVariables("MYAPP_ACCEPTANCE_");

this.configuration = configurationBuilder.Build();

NOTE that we have defined a prefix that environment variables must start with. This prefix will automatically be removed from the environment variable names by the configuration builder. This is a very useful feature as you can now store environment variables with the same name for multiple apps and/or environments.

Up to this point we will still get the same values if we get our config items as we have not set the values for any environment variables yet.

In C# .NET, working with environment variables is straightforward. The Environment class provides several methods for reading and setting environment variables. For example, to read an environment variable, you can use the Environment.GetEnvironmentVariable method, passing in the name of the variable you want to retrieve. To set an environment variable, you can use the Environment.SetEnvironmentVariable method, providing the name of the variable and its value. You can also use the command line to set the environment variables by running the SETX command.

For demonstration we will leave the value of MySettings:ApiUrl in appsettings.json

Next we will set the value of MySettings:ApiKey through this line of code

Environment.SetEnvironmentVariable("MYSETTINGS:APIKEY", "3d4a1c55-fcd7-4b34-8536-99c8ae6ae33c");

and for the MySettings:OrganisationId we will use the command line argument through a console window with administrative privileges

setx MYSETTINGS:ORGANISATIONID "b2440ae9-cad2-4d70-b138-4a807abe1bb7"

NOTE Visual Studio preloads the environment variables when it starts, and it caches them until the application is closed. Unlike environment variables set through code, those set using the command line will not be immediately available due to the preload behaviour. You will need to close Visual Studio and re-open it.

Once you have reloaded Visual Studio we can get the values from the configuration again by doing this:

    string apiUrl = configuration["MySettings:ApiUrl"];
    string apiKey = configuration["MySettings:ApiKey"];
    string organisationId = configuration["MySettings:OrganisationId"];

You will notice that the ApiUrl is the same as before, but the values have now changed for MySettings:ApiKey and MySettings:OrganisationId and they are now equal to the values we specified for the environment variables via code and through SETX on the command line.

You can also remove environment variables through code by setting the value to null.

Environment.SetEnvironmentVariable("MYSETTINGS:APIKEY", null);

OR via the command line you can do

setx MYSETTINGS:APIKEY /delete

Or if you prefer a GUI, you can also go to SYSTEM PROPERTIES > ENVIRONMENT VARIABLES where you can ADD / REMOVE environment variables.

This chapter lives on GitHub, where it is written in the open. Read the source or suggest a change.