.Net Core – appsettings.json files per environment

Depending on the environment, we may want different app settings. This is easily achieved in .Net Core.

First, you will have the default appsettings.json file. Any settings in here will apply to every environment.

Next, you can create a new appsetting.json file by right clicking on the project and adding a new item, select “App Settings File” and give it a name following this format: appsettings.{EnvironmentName}.json, e.g. appsettings.Development.json. This will create a nested app settings file beneath appsettings.json.

In this file you add any app settings for the Development environment.

Next we need to tell your app which appsettings.json file to use. We do this using Environment Variables, this is relatively simple but the method of getting the environment variables changes depending on the platform you are running on, these are shown in the code below.

The default Program.cs file will look like this:

public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build(); 
    }

We want to change this to the below, see the comments for explanations of each part. The code uses the correct appsettings.json file whether we’re running locally using launch settings profiles, on docker, on a server or on an Azure App Service:

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            const string environmentVariableName = "ASPNETCORE_ENVIRONMENT";
            var environmentName = Environment.GetEnvironmentVariable(environmentVariableName);//docker and local profiles need this
            if (string.IsNullOrEmpty(environmentName))
            {
                environmentName = Environment.GetEnvironmentVariable(environmentVariableName, EnvironmentVariableTarget.Machine);//server needs this
            }

            if (string.IsNullOrEmpty(environmentName))
            {
                environmentName = Environment.GetEnvironmentVariable($"APPSETTING_{environmentVariableName}");// Azure app service needs this
            }

            if (string.IsNullOrEmpty(environmentName))
            {//This makes it easier to see the error on app launch in azure app service
                environmentName = "Error: UNABLE TO DETERMINE THE VALUE OF ASPNETCORE_ENVIRONMENT";
            }

            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", false, true)
                .AddJsonFile($"appsettings.{environmentName}.json", false, true) //the false parameter here ensures there will be a run time error if the file isn't found
                .Build();

            return WebHost.CreateDefaultBuilder(args)
                .UseConfiguration(config)
                .UseStartup<Startup>();
        }
    }

Setting Environment Variables

There are different ways to set the environment variables.

If you are running the program via visual studio you can use launch setting profiles. These are very useful allowing you to quickly test using different environment configuration:

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "Test": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger/index.html",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Test"
      }
    },
    "Staging": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger/index.html",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Staging"
      }
    },
    "Dev-Local": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger/index.html",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development-Local"
      }
    }
  }
}

If you are running locally and not using launch profiles, e.g. executing the DLL using dotnet dllname.dll you will need to set the environment variable on the system. Using Windows 10:

  • Click the start menu and start typing “environment variables”, you will see an option for “Edit the system environment variables”, click it.
  • A System Properties window will open, on the Advanced tab, click “Environment Variables…”
  • In the System Variables section, add a new variable with name ASPNETCORE_ENVIRONMENT and value of whatever your environment is called as in the image below.
System Environment Variables

Docker and Azure App Services have their own ways of setting environment variables which I am not going to cover here.

When you run the program, the correct appsettings.json file should be used.

Leave a Reply

Your email address will not be published. Required fields are marked *