C# – How to read configuration from appsettings.json

The appsettings.json file is a convenient way to store and retrieve your application’s configuration. You can add it to any project and then use the Microsoft.Extensions.Configuration library to work with it. Since appsettings.json is just a JSON file, you can add any section / values you want (this is easier than working with XML-based app.config in earlier versions of .NET!).

In this article, I’ll show how to read configuration from appsettings.json in a console app and in ASP.NET Core.

Read config from appsettings.json in a console app

In this section, I’ll show how to read configuration values from appsettings.json in a console app.

1 – Add appsettings.json file

Appsettings.json is just a regular JSON file. To add it to the project:

  • Add a new item named appsettings.json and initialize it to an empty JSON file:
{
  
}
Code language: JSON / JSON with Comments (json)
  • Set appsettings.json to copy to the output folder (in the UI or in the csproj file):
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

Code language: HTML, XML (xml)

2 – Install configuration packages

Install the Microsoft.Extensions.Configuration.Json and Microsoft.Extensions.Configuration.Binder packages:

Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.Configuration.Binder
Code language: PowerShell (powershell)

Note: This is using Package Manager Console (from menu View > Other Windows > Package Manager Console).

3 – Add a custom config class

Add a class to load the configuration values into.

public class WeatherClientConfig
{
	public bool IsEnabled { get; set; }
	public string WeatherAPIUrl { get; set; }
	public string Timeout { get; set; }
}
Code language: C# (cs)

4 – Add values to appsettings.json

Add a section to appsettings.json with properties matching your custom config class.

{
  "WeatherClientConfig": {
    "IsEnabled": true,
    "WeatherAPIUrl": "https://localhost:12345",
    "Timeout": 5000
  }
}
Code language: JSON / JSON with Comments (json)

5 – Read the config section from appsettings.json

To read the custom config section from appsettings.json:

  • Use ConfigurationBuilder to build the Configuration object.
  • Use GetSection() to load the custom section.
  • Use Get<T>() to deserialize the JSON from the custom section.

Here’s an example of reading the WeatherClientConfig section into an object:

using Microsoft.Extensions.Configuration;

var config = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("appsettings.json").Build();

var section = config.GetSection("WeatherClientConfig");
var weatherClientConfig = section.Get<WeatherClientConfig>();

Console.WriteLine(weatherClientConfig.WeatherAPIUrl);
Console.WriteLine(weatherClientConfig.IsEnabled);
Console.WriteLine(weatherClientConfig.Timeout);
Code language: C# (cs)

As expected, this outputs the values from the WeatherClientConfig section in appsettings.json:

https://localhost:12345
True
5000Code language: plaintext (plaintext)

Read config from appsettings.json in ASP.NET Core

ASP.NET Core handles most of the work of reading config values for you. You mainly have to decide how you want to load the config values and how to pass them around. There are three options, which I’ll show below. Use whichever option suits you.

For these examples, I’ll show how to read the following custom section (WeatherClientConfig) from appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "WeatherClientConfig": {
    "IsEnabled": true,
    "WeatherAPIUrl": "https://localhost:12345",
    "Timeout": 5000
  }
}

Code language: JSON / JSON with Comments (json)

Option 1 – Use a custom config class

You can load the appsettings.json section into a custom config object. Then you can register it as a service and dependency inject it. I recommend this approach because it’s simple and keeps the configuration loading stuff (IOptions and IConfiguration) out of the rest of the code.

1 – Add custom config class

public class WeatherClientConfig
{
	public bool IsEnabled { get; set; }
	public string WeatherAPIUrl { get; set; }
	public string Timeout { get; set; }
}
Code language: C# (cs)

2 – Read the config section from appsettings.json

In the initialization code:

  • Use builder.Configuration.GetSection() to load the section from appsettings.json.
  • Use Get<T> to deserialize it to the custom config object.
  • Register it as service with builder.Services.AddSingleton().
using Microsoft.Extensions.Configuration;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

var section = builder.Configuration.GetSection("WeatherClientConfig");
var weatherClientConfig = section.Get<WeatherClientConfig>();

builder.Services.AddSingleton(weatherClientConfig);

var app = builder.Build();
Code language: C# (cs)

Note: Before .NET 6, do this in Startup.ConfigureServices().

3 – Dependency inject in controller

Add the custom config class as a constructor parameter wherever you need it.

[ApiController]
[Route("[controller]")]
public class ExampleController : ControllerBase
{
	private WeatherClientConfig config;

	public ExampleController(WeatherClientConfig config)
	{
		this.config = config;
	}

	[HttpGet]
	public IActionResult GetIsEnabled()
	{
		return Ok(config.IsEnabled);
	}
}
Code language: C# (cs)

Option 2 – Use options pattern

This approach uses the options pattern. This is useful in more complex scenarios where you need the full capabilities provided by IOptions.

1 – Add custom config class

public class WeatherClientConfig
{
	public bool IsEnabled { get; set; }
	public string WeatherAPIUrl { get; set; }
	public string Timeout { get; set; }
}
Code language: C# (cs)

2 – Configure with appsettings.json section

In the initialization code, use builder.Services.Configure() on the custom config section from appsettings.json.

using Microsoft.Extensions.Configuration;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

var section = builder.Configuration.GetSection("WeatherClientConfig");
builder.Services.Configure<WeatherClientConfig>(section);

var app = builder.Build();
Code language: C# (cs)

Note: Before .NET 6, do this in Startup.ConfigureServices().

This essentially registers IOptions<WeatherClientConfig> as a service.

3 – Dependency inject in controller

Add IOptions<WeatherClientConfig> as a constructor parameter wherever you need it.

using Microsoft.Extensions.Options;

[ApiController]
[Route("[controller]")]
public class ExampleController : ControllerBase
{
	private IOptions<WeatherClientConfig> config;

	public ExampleController(IOptions<WeatherClientConfig> config)
	{
		this.config = config;
	}

	[HttpGet]
	public IActionResult GetIsEnabled()
	{
		return Ok(config.Value.IsEnabled);
	}
}
Code language: C# (cs)

Notice that instead of directly using WeatherClientConfig, you use it via IOptions.

Option 3 – Use IConfiguration

If you don’t want to add a custom config class, you can dependency inject IConfiguration and use it to directly access values. Here’s an example:

[ApiController]
[Route("[controller]")]
public class ExampleController : ControllerBase
{
	private IConfiguration config;

	public ExampleController(IConfiguration config)
	{
		this.config = config;
	}

	[HttpGet]
	public IActionResult GetIsEnabled()
	{
		return Ok(config.GetValue<bool>("WeatherClientConfig:IsEnabled"));
	}
}
Code language: C# (cs)

Notice that you don’t need to do anything in the intialization code (IConfiguration is already registered as a service by ASP.NET Core).

Read a single value from appsettings.json

The sections above explained how to read a custom class from appsettings.json. What if you just want a single value?

Get a single value from a section

Let’s say your appsettings.json looks like this:

{
  "WeatherClientConfig": {
    "IsEnabled": true,
    "WeatherAPIUrl": "https://localhost:12345",
    "Timeout": 5000
  }
}
Code language: JSON / JSON with Comments (json)

To get WeatherClientConfig.IsEnabled (without getting the whole WeatherClientConfig object), you can use either of these two options:

//option 1 - GetValue(sectionName:key)
var weatherIsEnabled = config.GetValue<bool>("WeatherClientConfig:IsEnabled");

//option 2 - GetSection(sectionName) + GetValue(key)
var weatherIsEnabled = config.GetSection("WeatherClientConfig").GetValue<bool>("IsEnabled");
Code language: C# (cs)

Note: If the WeatherClientConfig section or the IsEnabled property is missing, then both of these options will return false.

Get a single top-level value

How about if you want to get a single value not contained in a section? For example, let’s say your appsettings.json looks like this:

{
  "Debug": true
}
Code language: JSON / JSON with Comments (json)

To get Debug, use this:

var debug = config.GetValue<bool>("Debug");
Code language: C# (cs)

Note: If the Debug property were missing from appsettings.json, this would return false.

Comments are closed.