How to read custom configs from appsettings

While writing a .NET application, we often need to create our own custom configurations and custom configs group (aka. Config Sections).

Assuming that you already have appsettings.json added into your project and you are already reading the configuration values from it,

Please follow along to know how to read the custom Config Section from the appsettings.json.

Create a public class that will be denoting the configurations that you are trying to group into a Config Section.

public class ServiceToMonitor
{
  public string Source { get; set; }
  public short Level { get; set; }
  public string MessageFormat { get; set; }

}

Add configurations matching to the class definition:

{
	"ServiceToMonitor": {
		"Source": "Application2",
		"Level": 2,
		"MessageFormat": "FormatRegex1"
	}
}

Or an array of custom configurations of the same type:

{
  "ServiceToMonitor": [
    {
      "Source": "Application1",
      "Level": 2,
      "MessageFormat": "FormatRegex1"
    },
    {
      "Source": "Application2",
      "Level": 2,
      "MessageFormat": "FormatRegex1"
    }
  ]
}

Make sure that you have installed the following two NuGet packages, if not please install these:

Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.Configuration.Binder

Now, using the ConfigurationBuilder to build the configuration object, then configs.GetSection() to read our custom class, then use Get<>() to deserialize it into your desired type. Here is the code snippet:

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

//Reading the custom configuration
var servicesToMonitor = config.GetSection(nameof(ServiceToMonitor))
                                .Get<List<ServiceToMonitor>>();

//Reading the array of custom configurations
var servicesToMonitor1 = config.GetSection(nameof(ServiceToMonitor))
                                .Get<List<ServiceToMonitor>>();

//Now use the read configuration simply as object
//servicesToMonitor.Source
//servicesToMonitor.Level
//servicesToMonitor.MessageFormat