How to Read appsettings.json in a .NET Console Application - Code Maze (2024)

Posted by Matheus Dasuke | Jul 4, 2024 | 0

SUMMER SALE – 50% OFF!

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API programand learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

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

Explanation Ofappsettings.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.

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

Addingappsettings.jsonto 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:

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.Configurationdotnet add package Microsoft.Extensions.Configuration.JsondotnetaddpackageMicrosoft.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.

SUMMER SALE – 50% OFF!

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API programand learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

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

How to Read appsettings.json in a .NET Console Application - Code Maze (2024)

References

Top Articles
Latest Posts
Article information

Author: Moshe Kshlerin

Last Updated:

Views: 6496

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Moshe Kshlerin

Birthday: 1994-01-25

Address: Suite 609 315 Lupita Unions, Ronnieburgh, MI 62697

Phone: +2424755286529

Job: District Education Designer

Hobby: Yoga, Gunsmithing, Singing, 3D printing, Nordic skating, Soapmaking, Juggling

Introduction: My name is Moshe Kshlerin, I am a gleaming, attractive, outstanding, pleasant, delightful, outstanding, famous person who loves writing and wants to share my knowledge and understanding with you.