Dotnet 3.1 appsettings & env variables

Reading apppsettings.json in dotnet 3.1

Add the packages

dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.FileExtensions
dotnet add package Microsoft.Extensions.Configuration.Json

Add appsettings.json file with required parameters

{
    "Settings": {
        "Params": {
            "Param1": "value 1",
            "Param2": "value 2"
        }
    }
  }

Load configuration section

Console app

// Program.cs
var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

IConfiguration configuration = builder.Build();

Use configuration

var param1 = configuration.GetSection("Settings").GetValue<string>("Params:Param1");

Web Api

// Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, configBuilder) => 
            {
                configBuilder
                    .AddJsonFile("appsettings.json", optional: false)
            }
        )
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

Use configuration by injecting it, for example in the controller.

[Route("[controller]")]
[ApiController]
public class HealthController : ControllerBase
{
    private readonly IConfiguration _configuration;

    public HealthController(IConfiguration configuration)
    {
        _configuration = configuration;
    }
}

Using multiple app settings sources

Console app

Add package for Environment Variables too.

dotnet add package Microsoft.Extensions.Configuration.EnvironmentVariables

Add another appsettings.json and environment variables. If a value is present in more than one source, last one applied wins.

var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile("appsettings.secrets.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();

Web Api appsettings per environment.

// Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, configBuilder) => 
            {
                configBuilder
                    .AddJsonFile("appsettings.json", optional: false)
                    .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true);
            }
        )
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

The hostingContext.HostingEnvironment.EnvironmentName is loaded from environment variale ASPNETCORE_ENVIRONMENT.