In this article, we will learn how to read appsettings.json in a .NET console application.

Explanation Of appsettings.json

The appsettings.json file in .NET applications serves as a centralized repository for configuration settings, utilizing the JSON format for its simplicity and readability. It includes various hierarchically organized sections, such as logging levels, connection strings, and custom application settings. This file is essential for managing environment-specific configurations. It simplifies transitioning between development, testing, and production environments without modifying the codebase. Also, it supports dynamic reloading of settings—real-time changes in the configuration values while the application is running. By separating configuration data from code, appsettings.json enhances maintainability. Overall, appsettings.json plays a crucial role in the configuration management of .NET applications, promoting flexibility, consistency, and ease of deployment.

Adding appsettings.json to the Project

After we create a new console application, we will need to add an appsetting.json to our project. Using Visual Studio, we can right-click on our project and select the option to add a new file, after that, we select the JSON option and give a name to it, in that case, appsettings.json

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

How to Read appsettings.json in a .NET Console Application

So, we can populate our appsettings.json with a few examples that we will retrieve later:

{
  "Settings1": "Hello there",
  "AppSettings": {
    "Settings2": "Hello from nested configuration section!"
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=10.1.1.120;Database=Database;User=Admin;Password=MyStrongPassword;"
  }
}

Now, let’s continue to set up our project to be able to read the data from the appsettings.json.

To learn more about how to create a console application using CLI, check out our Using the CLI to Build and Run .NET Applications article.

Installing Necessary Nuget Packages

We will need to install three NuGet packages to be able to read the data from the appsettings.json, we can install them via the NuGet Package Manager or using the Package Manager Console:

dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.Json
dotnet add package Microsoft.Extensions.Configuration.Binder

The first two packages will provide the option to read the data from the configuration file and the Microsoft.Extensions.Configuration.Binder will provide the option to bind configuration sections to strongly typed objects.

Configuring the Program to Read appsettings.json in .NET

In our Program.cs, we will need to add the code to be able to read the data from the appsettings.json:

using Microsoft.Extensions.Configuration;

var builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory())
       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

IConfigurationRoot configuration = builder.Build();

Here, we are setting up our configuration file. The SetBasePath(Directory.GetCurrentDirectory()) sets the base path for the configuration file to the current directory where the application is running. The AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) adds the appsettings.json file as a configuration source, optional: false means the file is required and the application will throw an error if it does not exist or is not found. The last parameter, reloadOnChange: true, enables the configuration to automatically reload if the appsettings.json file is modified while the application is running, allowing for dynamic updates to the configuration settings without restarting the application.

Accessing Configuration Sections

Accessing configuration sections involves retrieving nested configuration values by specifying their keys or by binding them to strongly typed objects.

Let’s learn about them.

Specifying Keys

We are ready to read any data from our appsettings.json, so let’s read the first example from our JSON file, which will be the settings1:

var example1 = configuration["Settings1"];
Console.WriteLine(example1);

var example1UsingSection = configuration.GetSection("Settings1");
Console.WriteLine(example1UsingSection.Value);

As we can see, we define two variables, example1 and example1UsingSection, which receives the data from the configuration file and prints them to the console.

In our second example, we will learn how to read from a nested configuration:

var settings = configuration["AppSettings:Settings2"];
Console.WriteLine(settings);

var settings2 = configuration.GetSection("AppSettings");
Console.WriteLine(settings2["Settings2"]);

Here, we have two variables to receive the data from the configuration file and print them to the console.

In our last example specifying the keys, we will retrieve a connection string:

var connectionString = configuration.GetConnectionString("DefaultConnection");
Console.WriteLine(connectionString);

So, we can use the configuration.GetConnectionString to help us to retrieve the connection string from appsettings.json. Then, we assign the result to a variable just for learning purposes.

Read appsettings.json in a .NET With Strongly Typed Class

 We will need to create a class to map the fields from the configuration file, they need to match the structure of the section in the appsettings.json. So, we will create a class called AppSettings to bind the configuration to a strongly typed object:

public class AppSettings
{
    public string Settings2 { get; set; }
}

Then, we are going to bind the section, AppSettings, to our class:

configuration.GetSection("AppSettings").Bind(appSettings);
Console.WriteLine(appSettings.Settings2);

This approach ensures our configuration is strongly typed and easily accessible throughout our application. So that eliminates the need to specify keys directly.

Conclusion

In this article, we have learned how to read appsettings.json in a .NET and how it is crucial for .NET applications as it provides a centralized and organized way to manage application settings and configuration. It promotes maintainability and flexibility, allowing developers to modify settings without changing the code. It is particularly beneficial for adjusting environment-specific configurations such as connection strings, API keys, and feature flags.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!