C# – How to read custom configurations 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 anything to it (as long as it’s valid JSON). Compared with working with the XML-based app.config from earlier versions of .NET, dealing with customizations in appsettings.json is simpler and more flexible.

This article shows step by step how to add custom configurations to appsettings.json and how to load your customizations with steps specific to the type of project you’re working in (ASP.NET Core vs everything else).

Reading a custom class from appsettings.json in a Console App (or any project besides ASP.NET Core)

If you’re not working in ASP.NET Core, then you have to do a little bit more work to be able to read values from appsettings.json. Basically you have to add the appsettings.json file, add the configuration extension packages, initialize the configuration object, then read your custom values from the config.

1 – Add appsettings.json file

There’s nothing special about this file. It’s just a JSON file. To add it to any project:

  • Add new item.
  • Name it appsettings.json.
  • Initialize it as an empty JSON file:
{ }
  • Make it copy appsettings.json to the output folder. You can do this in the UI, or by adding the following to 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>

2 – Install configuration nuget packages

  • Open Package Manager Console (View > Other Windows > Package Manager Console)
  • Install the packages:
Install-Package Microsoft.Extensions.Configuration.Json Install-Package Microsoft.Extensions.Configuration.Binder

This’ll pull the latest packages and put the package references in your .csproj file:

<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.1</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="3.1.9" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.9" /> </ItemGroup> <ItemGroup> <None Update="appsettings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> </Project>

3 – Add a custom class – WeatherClientConfig

public class WeatherClientConfig { public bool IsEnabled { get; set; }; public string WeatherAPIUrl { get; set; } public string Timeout { get; set; } }

4 – Add the custom class JSON to appsettings.json

{ "WeatherClientConfig": { "IsEnabled": true, "WeatherAPIUrl": "https://localhost:12345", "Timeout": 5000 } }

5 – Read the custom config from appsettings.json

To read the custom config, use ConfigurationBuilder to build the configuration object. Then use configuration.GetSection() to get your custom class JSON, then use Get<T>() to deserialize it into your custom class.

As you can see below, all of the hard work is abstracted away thanks to the Microsoft.Extension.Configuration packages.

using Microsoft.Extensions.Configuration; using System; namespace ReadingAppSettingsJson { class Program { static void Main(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json").Build(); var section = config.GetSection(nameof(WeatherClientConfig)); var weatherClientConfig = section.Get<WeatherClientConfig>(); Console.WriteLine(weatherClientConfig.WeatherAPIUrl); Console.WriteLine(weatherClientConfig.IsEnabled); Console.WriteLine(weatherClientConfig.Timeout); } } }

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

https://localhost:12345 True 5000

Reading a custom class from appsettings.json in ASP.NET Core

The ASP.NET Core framework does most of the work for you. By default, it has the configuration packages as references, has the appsettings.json file included in the project, and it already initializes the Configuration object from appsettings.json.

You just need to add your customizations to appsettings.json, optionally create a custom class, and then load it in Startup.ConfigureServices.

To make this explanation consistent with how I showed how to do it in a Console App, I’m using a custom class – WeatherClientConfig.

Note: If you don’t want to add your own custom class, you could use services.Configure(customSection) and dependency inject IOptions instead. I’m showing the custom class approach here.

1 – Add a custom class

public class WeatherClientConfig { public bool IsEnabled { get; set; }; public string WeatherAPIUrl { get; set; } public string Timeout { get; set; } }

2 – Add the custom class JSON to appsettings.json

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

3 – Register the custom class in Startup.ConfigureServices

public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddControllers(); var section = Configuration.GetSection(nameof(WeatherClientConfig)); var weatherClientConfig = section.Get<WeatherClientConfig>(); services.AddSingleton(weatherClientConfig); } //The rest of Startup class }

4 – Dependency inject the custom class into a controller

Take advantage of the ASP.NET Core dependency injection functionality. Because of registering WeatherClientConfig in the services collection in the previous step, anything that has WeatherClientConfig as a dependency (i.e. constructor parameter) will automatically get the registered object passed to it.

So add the WeatherClientConfig as a parameter in a controller, and add a GET endpoint that simply returns this configuration (so you can see it working with a simple GET request).

[ApiController] [Route("[controller]")] public class WeatherController : ControllerBase { private readonly WeatherClientConfig weatherClientConfig; public WeatherController(WeatherClientConfig weatherClientConfig) { this.weatherClientConfig = weatherClientConfig; } [HttpGet] public WeatherClientConfig Get() { return weatherClientConfig; } }

When I do a GET request on this endpoint, I get the WeatherClientConfig JSON back:

{ "isEnabled": true, "weatherAPIUrl": "https://localhost:12345", "timeout": "5000" }

Reading 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?

  • Add the single value to appsettings.json.
{ "Debug": true }
  • Load it like this:
var debug = config.GetSection("Debug").Value;

Leave a Comment