In .Net Core 2 or .Net Core 3, the steps to add support for reading JSON configuration files are as follows:
Step1: Install Nuget Packages
Install the following Nuget Packages:
- Microsoft.Extensions.Configuration.Json
- Microsoft.Extensions.Configuration.Binder
Step 2: Set up JSON configuration file
Then you will need to create an appSettings.json file (name of the file can be anything) in the root directory of the project. This file contains your JSON configuration. For this example, we will use the following minus the other double quotation marks as the content of our appSettings.json :
"
{
"App": {
"Title": "My App",
"Message": "Hello World",
"Version": 1
}
}
"
Step 3: Add Build Configuration Code
Use the Configuration Builder class to read the appSettings.json file to access the json configuration
var builder = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appSettings.json");
var configuration = builder.Build();
The above code does the following for the configuration builder:
- Sets the base path of the configuration builder to the same directory as the .net core console application
- Add the JSON file, appSettings.json, in the base directory as a configuration source
- Build the configuration builder to get the configuration object for fetching the configuration and store the object in a variable named configuration
Step 4: Accessing values in the json file
We use the configuration variable to access values stored in the appSettings.json file. There are many ways to access the values. My personal preference is to strongly type bind the json settings with a model class.
To do that, you will need to create class as a model for the json setting to bind with. For our example, we will bind the settings in our appSettings.json with the following class named AppOptions:
public class AppOptions
{
public string Title { get; set; }
public string Message { get; set; }
public int Version { get; set; }
}
Final Step: Bind json settings with a strongly typed model
To strongly bind the json settings with the model we created, we need to download the Nuget Package Microsoft.Extensions.Configuration.Binder. We then use the following code:
var appOptions = configuration.GetSection("App").Get<AppOptions>();
The above code is asking the program to read the JSON under App section in the appSettings.json and bind it to AppOptions model class.
The final overall code will look like the following:
var builder = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appSettings.json");
var configuration = builder.Build();
var appOptions = configuration.GetSection("App").Get<AppOptions>();
Console.WriteLine(appOptions.Title);
Console.WriteLine(appOptions.Message);
Console.WriteLine(appOptions.Version);
The above program will return the following result when executed:
My App
Hello World
1