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 a web.config file, but in the 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 the 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.

"MySettings": {  
    "DbConnection": "abc",  
    "Email": "[email protected]",  
    "SMTPPort": "5605"  
  }  

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.

[HttpGet]  
public IActionResult GetUsers()  
{  
var list = new List<string>();  
       list.Add("John");  
       list.Add("Doe");  
       return Ok(list);  
 }  

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 the input parameter “IConfiguration”.

public UserController(IConfiguration iConfig)  
{  
   configuration = iConfig;  
}  

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 the appsettings.json file.

There are two methods to retrieve our values,

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.

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 the 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).

public class MySettingsModel  
{  
public string DbConnection { get; set; }  
       public string Email { get; set; }  
       public string SMTPPort { get; set; }  
}  

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 the ConfigureServices method, we will register our class by writing the below code.

services.Configure<MySettingsModel>(Configuration.GetSection("MySettings"));  

Note. In the 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.

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.

public StudentController(IOptions<MySettingsModel> app)  
{  
    appSettings = app;  
}  

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 the 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.