Web Development

How to Read AppSettings Values From a JSON File in .NET Core

In this post, we are going to learn how to read AppSettings values from a JSON file in ASP.NET Core.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

Read AppSettings Values From JSON File

Enabling a feature in ASP.NET Core almost always starts with configuring relevant components into the DI pipeline. This is also true for reading application settings from a JSON file. The good thing is that ASP.NET Core provides extra flexibility here. As long as we use the conventional filename, i.e. appsettings.json, we don’t need any explicit setup for it. DI system will do it internally for us. In a later section, we will see how we can set up a different filename.

So, let’s assume we have an appsettings.json file that defines some formatting options for our API:

{
  "AllowedHosts": "*",
  "Formatting": {
    "Localize":  false,
    "Number": {
      "Format": "n2",
      "Precision": 3
    }
  }
}

As we run the application, DI framework automatically pulls this piece of data in IConfiguration service.

Read Values From IConfiguration

To see IConfiguration in action, let’s add an API controller:

public class ConfigurationDemoController : ControllerBase
{
    private readonly IConfiguration _configuration;

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

    [HttpGet("formatting/islocalized")]
    public bool GetIsLocalized()
    {
        var localize = _configuration.GetValue<bool>("Formatting:Localize");

        return localize;
    }
}

We start with injecting IConfiguration in the constructor. Later inside the GetIsLocalized endpoint, we can retrieve the “Localize” option by calling _configuration.GetValue(). To do this, we have to specify the full path of the target json-node, notably with “:” as the child node accessor.

We can extract the value of “Precision” similarly:

var precision = _configuration.GetValue<int>("Formatting:Number:Precision");

Pulling the whole “Formatting” group is also possible – by using a POCO model that resembles the target JSON tree.

The FormatSettings:

public class FormatSettings
{
    public bool Localize { get; set; }

    public NumberSettings? Number { get; set; }
}

And the NumberSettings:

public class NumberSettings
{
    public string? Format { get; set; }

    public int Precision { get; set; }
}

Now, we can easily map the “Formatting” section to a FormatSettings instance:

var formatSettings = _configuration.GetSection("Formatting").Get<FormatSettings>();

This way of extracting group configurations is quite convenient. But not as much as it would with Options Pattern, especially if we need it in multiple places.

Using Options Pattern

To start using the options pattern for reading FormatSettings, we need to configure it with DI first.

Let’s do it in Program class:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.Configure<FormatSettings>(builder.Configuration.GetSection("Formatting"));
builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();

All we need is to add the highlighted line in this boilerplate code. With the help of the Configure() extension method, we establish the “Formatting” section as the data source of FormatSettings.

This enables easy access to FormatSettings just by injecting IOptions<FormatSettings> anywhere we need it:

public class OptionsDemoController : ControllerBase
{
    private readonly FormatSettings _formatSettings;

    public OptionsDemoController(IOptions<FormatSettings> options)
    {
        _formatSettings = options.Value;
    }

    [HttpGet("formatting")]
    public FormatSettings Get() => _formatSettings;
}

This is much simpler and the recommended way to deal with configuration groups.

Register JSON File With Unconventional Name

It’s time to see how to register an arbitrary JSON configuration file. 

So, if we want to set up a “config.json” file as the source of application configuration:

// Add services to the container.
builder.Host.ConfigureAppConfiguration(config =>
{
    config.AddJsonFile("config.json");
});
builder.Services.Configure<FormatSettings>(builder.Configuration.GetSection("Formatting"));
builder.Services.AddControllers();

We can register it using a host configurator extension named  ConfigureAppConfiguration. Inside its closure, we just need to call AddJsonFile(). As simple as that.

Read AppSettings Outside of DI

Sometimes we need to read configurations outside of ASP.NET Core DI. This is a typical case when we work with design time execution or CLI tools like generating database migration files (Entity Framework Core) for example.

Dependencyless ConfigurationBuilder class comes in handy for such cases:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("config.json")
    .Build();

var precision = configuration.GetValue<int>("Formatting:Number:Precision");

We can get a default IConfiguration just by adding the target json file to the builder. The rest is no different than our previous examples.

Conclusion

In this article, we have discussed various approaches to read configurations from a JSON file in ASP.NET Core.

Ahsan Ullah

Share
Published by
Ahsan Ullah

Recent Posts

Code Maze Weekly #149

Issue #149 of the Code Maze weekly. Check out what's new this week and enjoy…

Updated Date Nov 25, 2022

C# String Interpolation

Very early in the history of programming, we've seen the need to use text on…

Updated Date Nov 24, 2022

How to Check if a String Ends With a Number in C#

Checking if a string ends with a number in C# is a very common operation.…

Updated Date Nov 25, 2022

How to Execute Stored Procedures With EF Core 7

In this article, we will see how to use stored procedures in Entity Framework Core…

Updated Date Nov 22, 2022

HashSet vs SortedSet in C#

The HashSet<T> and SortedSet<T> classes in the System.Collections.Generic namespace define two ways of storing and iterating…

Updated Date Nov 22, 2022

Code Maze Weekly #148

Issue #148 of the Code Maze weekly. Check out what's new this week and enjoy…

Updated Date Nov 18, 2022