Read appsettings.json Config in ASP.NET Core

When developing an ASP.NET Core application, it's important to be able to define a group of settings, and be able to read those settings within the application.

With this example, you will be able to read the settings inside your appsettings.json file, and use them in your application

There will be three different ways in how to retrieve a setting from a configuration file.

This will include being able to convert your settings into a strongly typed class. You will also be able to validate this class using data annotations.

In addition, there is an example of being able to separate each config section into it's own separate file.

And, if you wish to use a database, there is a way of storing the SQL Server connection string and reading it in the application.

If you need a console application for a background task for example, there is a way of reading the appsettings.json file into a console application.

Software

This is the software that will need to be installed onto your machine.

Get The Application Working

These are the steps to get the application working.

The ASP.NET Core MVC Application

The ASP.NET Core MVC application is located in the RoundTheCode.AppSettings.Web folder.

Open up RoundTheCode.AppSettings.Web.sln in Visual Studio.

You should find that the web application runs on https://localhost:5000.

Start the project in Visual Studio.

You can see the three reading of the configuration file examples with these links:

  • https://localhost:5000/appsettings/first-way
  • https://localhost:5000/appsettings/second-way
  • https://localhost:5000/appsettings/third-way

If you wish to test out the connection strings, you need to do the following:

  • Inside the source code, there is a folder called Database. Within that folder, there is a file called RoundTheCodeSync.bak. This needs to be imported as a database into your SQL Server.
  • Open up RoundTheCode.AppSettings.Web\ RoundTheCode.AppSettings.Web\ appsettings.json and change the connection string that's in ConnectionStrings > SyncDb.
  • Then run the application in Visual Studio and navigate to https://localhost:5000/appsettings/database.

Console Application

The Console application is located in the RoundTheCode.AppSettings.ConsoleApp folder.

Open up RoundTheCode.AppSettings.ConsoleApp.sln in Visual Studio.

Start the project in Visual Studio.

More Information

You can read more information by viewing our "How to Read The appsettings.json Configuration File in ASP.NET Core" article.

In-addition, watch our video tutorial, where we test out how to get the settings from the appsettings.json file into our ASP.NET Core application.

Join our Discord server

  • Can't get your ASP.NET Core application to work? Ask for help here!
  • Discussions with other ASP.NET Core developers.
  • General chat with the community.
Join Discord