Reading Values From Appsettings.json In ASP.NET Core

Introduction

 
In today’s article, we will see how to read values from appsettings.json in ASP.NET Core similar to what we used to do in ASP.NET MVC by reading values from web.config. 
 
Why do we need this?
 
In a complex application, there are several constants that need to be used throughout an application but we just cannot simply hard-code them at every place we need because if we need to change some value, then we will have to visit each and every place where it is used, and change it, which can be very risk-prone as we are bound to miss some.
 
Hence, to solve this issue, we keep such constants in a single location and access them wherever we need them.
 
In ASP.NET MVC, we used to keep such information in web.config file, but in ASP.NET Core application, there is no such thing as web.config.
 
So, how do we do it?
 
There is a file present for this purpose only which is called appsettings.json. We define our values in that file in key-value pairs and then we use them as per our needs. So okay, let’s get started.
 
We will create ASP.NET Core project first.
 
ASP.NET Core
 
Then, we will pick API as our template (This is just a demonstration, you can pick any template you want).
 
ASP.NET Core
 
 Once the project is created, we will add an API Controller.
 
ASP.NET Core
 
Now, we will open the appsettings.json file and add our own keys with their values.
 
I have added the following JSON object.
  1. "MySettings": {  
  2.     "DbConnection""abc",  
  3.     "Email""abc@domain.com",  
  4.     "SMTPPort""5605"  
  5.   }  
My modified file looks like this.
 
ASP.NET Core
 
Now, in our Controller that we created earlier, we will add a method so that we can test our code.
 
My dummy method looks like this.
  1. [HttpGet]  
  2. public IActionResult GetUsers()  
  3. {  
  4. var list = new List<string>();  
  5.        list.Add("John");  
  6.        list.Add("Doe");  
  7.        return Ok(list);  
  8.  }  
Now, in our cController, we will add a private field of type “IConfiguration” which is found in Microsoft.Extensions.Configuration namespace, so we need to add that namespace in our file.
 
Now, we will create a constructor of our Controller with input parameter “IConfiguration”.
  1. public UserController(IConfiguration iConfig)  
  2. {  
  3.    configuration = iConfig;  
  4. }  
ASP.NET Core
 
The part you see in yellow is just a dummy method to get called when we run this API Controller. Now, we are all set up to get the values of our custom keys that we have defined in appsettings.json file.
 
There are two methods to retrieve our values,
  1. string dbConn = configuration.GetSection("MySettings").GetSection("DbConnection").Value;  
In the first method, we are getting our section from the configuration object. Inside this, we are getting another section that contains the value.
  1. string dbConn2 = configuration.GetValue<string>("MySettings:DbConnection");  
In the second method, we are directly getting the string type value from the configuration object. We are separating our nested sections by “:”.
 
So our modified Controller will look something like this.
 
ASP.NET Core
 
And below are the results of both methods.
 
Value from method 1
 
ASP.NET Core
 
Value from method 2
 
ASP.NET Core
 
So, in this way, you can get any values from appsettings.json file.
 
But this method is not performance-friendly because as you can see by the code above, we will load the entire configuration every time our controller is called basically.
So, there is a better to do this by just getting the things you need. Let’s see how we can implement this.
 
We will create a model in which we will define properties with the same name as we have defined in our appsettings.json. So, my model looks like this. (I have added a folder called models and inside it, placed my class MySettingsModel just so that code looks a bit cleaner).
  1. public class MySettingsModel  
  2. {  
  3. public string DbConnection { get; set; }  
  4.        public string Email { get; set; }  
  5.        public string SMTPPort { get; set; }  
  6. }  
ASP.NET Core
 
So, now in order to bind our class with our keys in appsettings.json, we need to register our defined section with our class in DI container. In order to do that, we will go to Startup.cs file and in ConfigureServices method we will register our class by writing the below code.
  1. services.Configure<MySettingsModel>(Configuration.GetSection("MySettings"));  
Note
 
In GetSection method, your string should be the same as defined in appsettings.json and MySettingsModel is the class that I just created.
 
ASP.NET Core
 
Now, to demonstrate this method, I have created another Controller (StudentController), just to distinguish between the two approaches.
 
So, in the Controller, we will define a private property of return type IOptions<MySettingsModel>. IOptions can be found in Microsoft.Extensions.Options namespace so we need to import that above our file.
  1. private readonly IOptions<MySettingsModel> appSettings;  
So, our updated controller will look like this.
 
ASP.NET Core
 
Here again, I have implemented a dummy method so that we can test our API.
 
After this, we will create a constructor of our controller with IOptions<MySettingsModel> as an input parameter.
  1. public StudentController(IOptions<MySettingsModel> app)  
  2. {  
  3.     appSettings = app;  
  4. }  
ASP.NET Core
 
As you can see appSettings.Value. is showing all our properties that are defined in our model. Now, when we run it, we can see the values.
 
ASP.NET Core
 
  ASP.NET Core

Summary

 
In this article, we have seen two approaches to read the values from the appsettings.json file.
 
Both approaches are easy to implement and use but I would recommend you choose IOptions method because in the grand scheme of things your code will be cleaner and performance will be better.
 
But that is just my opinion, you can implement whatever method you like.
 
Happy Coding.