wsf

wsf

How to use the appsettings.json configuration file?

In a .NET Core project, we can use the appsettings.json configuration file to store application configuration information. In this article, we will learn how to use the appsettings.json configuration file.

appsettings.json is a more flexible configuration file compared to App.config, and it is a new configuration method introduced since .NET Core, providing more flexibility.

Quick Start#

We can create an appsettings.json file in the project and set its file copy options to "Copy if newer" or "Copy always," so that when the project is built, the appsettings.json file will be copied to the output directory.

Then we can add the following content to it:

{
    "AppSettings": {		
        "LogLevel":"Warning",
        "ConnectionStrings": {
            "Default": "this is the connection string"
        }	
    }
}

This way, we can try to read it. We use the NuGet package manager to install the Microsoft.Extensions.Configuration.Json package. It will implicitly install dependencies like Microsoft.Extensions.Configuration, which we do not need to install explicitly.

Then we can read the configuration file in the code:

using Microsoft.Extensions.Configuration;

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

This way we can retrieve the configuration information above:

var logLevel = configuration["AppSettings:LogLevel"];
var connectionString = configuration["AppSettings:ConnectionStrings:Default"];

The format like AppSettings.LogLevel is a special notation that simply uses : to represent the hierarchical relationship in JSON.

If the configuration item we want to retrieve is a number, we can either first get it as a string using the above method and then convert it using int.Parse or Convert.ToInt32, or we can use the GetValue method:

// Traditional method
var logLevel = int.Parse(configuration["AppSettings:LogLevel"]);
// Using GetValue method
var logLevel = configuration.GetValue<int>("AppSettings:LogLevel");

For connection strings, we can also use the GetConnectionString method:

var connectionString = configuration.GetConnectionString("Default");

Optional and Auto-Reload#

In the code above, we can see that the AddJsonFile method has two parameters, optional and reloadOnChange:

  • The optional parameter indicates whether the configuration file is allowed to be absent. If set to false, it will throw an exception; otherwise, it will be ignored.
  • The reloadOnChange parameter indicates whether to reload the configuration file when it changes. If set to true, it will reload the configuration file when it changes.

For example, we can test the auto-reload effect with the following example:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

while (true)
{
    Console.WriteLine(configuration["AppSettings:LogLevel"]);
    Thread.Sleep(1000);
}

After running the program, we can modify the LogLevel configuration in the appsettings.json file, and we will find that the program automatically reloads the configuration file. Note that we are modifying the appsettings.json file in the output directory (where the .exe file is located), not the appsettings.json file in the project.

Adding Multiple JSON Files#

If we could only add one JSON file, the flexibility of the configuration file would be greatly reduced. In fact, we can add multiple JSON files by calling the AddJsonFile method multiple times. A typical scenario is to add an appsettings.Development.json file to store configuration information for the development environment.

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
    .Build();

This way, we can store configuration information for the development environment in the appsettings.Development.json file, while storing general configuration information in the appsettings.json file.

Moreover, there is a priority or overriding relationship between the two. Specifically:

  • If both appsettings.json and appsettings.Development.json contain the same configuration item, the configuration item in appsettings.Development.json will override the one in appsettings.json.
  • If a configuration item is not present in appsettings.Development.json but is present in appsettings.json, the configuration item from appsettings.json will be used.
  • If a configuration item is present in appsettings.Development.json but not in appsettings.json, the configuration item from appsettings.Development.json will be used.

Using Strongly Typed Configuration#

In the example above, we used configuration["AppSettings:LogLevel"] to retrieve configuration information, which is a weakly typed approach. We can also use a strongly typed approach to retrieve configuration information.

We modify the configuration items in the appsettings.json file:

{
    "UserSettings": {
        "Name": "Alice",
        "Age": 18,
        "IsActive": true
    }
}

Then we define a strongly typed configuration class:

public class UserSettings
{
    public string Name { get; set; }
    public int Age { get; set; }
    public bool IsActive { get; set; }
}

Before retrieving the configuration, we also need to install a NuGet package: Microsoft.Extensions.Options.ConfigurationExtensions. Then we can retrieve the configuration information like this:

var userSettings = configuration.GetSection("UserSettings").Get<UserSettings>();

This way, we can obtain the UserSettings object, and then we can use userSettings.Name, userSettings.Age, and userSettings.IsActive to access the configuration information.

However, it is important to note that since the userSettings instance has already been initialized, the auto-reload feature mentioned earlier will no longer be effective. If we need auto-reload, we need to retrieve the userSettings object again.

Adding Environment Variables and Command Line Arguments#

In .NET Core, we can also override configuration information in the configuration file using environment variables and command line arguments. We need to install two more NuGet packages:

  • Microsoft.Extensions.Configuration.EnvironmentVariables
  • Microsoft.Extensions.Configuration.CommandLine

Then we can add environment variables and command line arguments like this:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables()
    .AddCommandLine(args)
    .Build();

This way, we can override the configuration information in the configuration file using environment variables and command line arguments.

For example, we can create a .bat batch file:

@echo off
set UserSettings__Name=Bob
set UserSettings__Age=20

.\Demo.exe

Or we can use PowerShell:

$env:UserSettings__Name = "Bob"
$env:UserSettings__Age = 20

.\Demo.exe

Summary#

I believe that through this article, everyone has recognized the power of the appsettings.json configuration file. It not only provides a flexible configuration method but also offers a combination of various configuration methods, allowing us to configure applications more flexibly.

However, it also has some limitations. The most important one is that its configuration items are "read-only," meaning they cannot be easily modified at runtime like App.config. After all, a project may have multiple configuration items, not just one appsettings.json file. In this case, if modifications are made, which file should they be saved to?

Of course, if there is only one configuration file, then appsettings.json is a good choice. For example, we can use Newtonsoft.Json to easily write to JSON files, allowing for modifications to configuration items.

Finally, in most cases, we do not use the above method to read configuration items; instead, we go further by using Host as the entry point for the entire program, reading configurations, injecting services, etc. In future articles, we will learn how to use Host to build a .NET application.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.