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.

16 thoughts on “C# – How to read configuration from appsettings.json”

  1. After many hours scratching around trying to access my custom configuration within my IHostBuilder CreateHostBuilder(string[] args) method this finally gave me the simplest answer I was looking for!

    Bravo!

    Reply
  2. Great article, thanks – moved to Core from ‘old’ .NET and getting nowhere with settings until I read this!

    Reply
  3. Hello,

    Thanks for information for custom configuration. But I need to use it with ASP.NET Core Razor Pages, I’m not using MVC.

    I’m new to ASP.NET Core, so not sure to integrate in Razor pages. There are few issues :
    1. is there any way to handle it without MVC?
    2. I’m using latest version of ASP.NET Core 6.0 and there are no Startup.cs file any more.

    Awaiting for response.

    Reply
    • Hi,

      1. Follow the first two original steps since they’re the same (add a custom class + put settings in appsettings.json).

      2. Because you’re using the new project template (where everything is in Main()), read the config and register the custom config class in Main():

      public static void Main(string[] args)
      {
          
          var builder = WebApplication.CreateBuilder(args);

          builder.Services.AddRazorPages();
          
          //step 1 – Read from config file
          var section = builder.Configuration.GetSection(nameof(WeatherClientConfig));
          var weatherClientConfig = section.Get<WeatherClientConfig>();

          //step 2 – Register config instance with DI container
          builder.Services.AddSingleton(weatherClientConfig);

          var app = builder.Build();

          //rest of the code
      }

      3. Now here’s the part that’s different for Razor Pages.
      First, add the custom config class as a constructor parameter (this enables constructor injection):

      public class IndexModel : PageModel
      {
          public readonly WeatherClientConfig WeatherClientConfig;

          public IndexModel(WeatherClientConfig weatherClientConfig)
          {
              WeatherClientConfig = weatherClientConfig;
          }
      }

      Now you can use this in the Model or Page. Here’s an example of displaying a property from the config on the page:

      @page
      @model IndexModel

      <div>
          <h1>@Model.WeatherClientConfig.WeatherAPIUrl</h1>
      </div>

      Reply
  4. Hi when i run my app , section.Get() returns null and i don’t know the reason.
    Can i have the help please?

    Reply
    • Hi Raphael,

      section.Get() returns null if it’s an empty IConfigurationSection. When you use config.GetSection(), it returns an empty IConfigurationSection if the section doesn’t exist in the appsettings.json.

      Check three things:
      1. Verify you are using the right name with config.GetSection():
      var section = config.GetSection("ThisIsTheWrongName"); //This would return an empty IConfigurationSection since it’s the wrong name
      var weatherClientConfig = section.Get<WeatherClientConfig>();

      2. If you’re using the right name with config.GetSection(), then verify that the section exists in appsettings.json.

      3. If it exists and the name is right, then you’re probably loading the wrong appsettings.json accidently (or it isn’t being copied to the build output folder, so doesn’t have your class in it).

      You can print out the file path for troubleshooting:

      var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
      Console.WriteLine("File is here: " + filePath);

      Go take a look at the file and see if it’s what you expect.

      Note: I’m assuming you’re using AppDomain.CurrentDomain.BaseDirectory.

      If you’re still having trouble, feel free to reply and share the relevant parts of your code (including appsettings.json).

      Reply
  5. What if your appsettings.json has an array of items in it. I’m having trouble with this.

    var result = config.GetValue<List<Restriction>>(“MyCorp:Restriction”);

    {
    “MyCorp”: {
    “Restriction”: [
    {
    “Company”: “ABC”,
    “Account”: 8999
    },
    {
    “Company”: “XYZ”,
    “Account”: 8988
    }
    ]
    }
    }

    Reply
    • Hi,

      Instead of GetValue, use GetSection + Get, like this:

      var section = config.GetSection("MyCorp:Restriction");
      var restrictionList = section.Get<List<CompanyAccount>>();

      foreach(var ca in restrictionList)
      {
          Console.WriteLine($"{ca.Company}={ca.Account}");
      }

      Reply

Leave a Reply to Maclain Wiltzer Cancel reply