Search
  • Ravi Raghav

Reading values from appsettings.json in ASP.NET Core

In today’s article, we will see how to read values from appsettings.json in ASP.NET Core similarly to what we used to do in ASP.NET MVC by reading values from web.config.

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



Then we will pick API as our template. (This is just a demonstration, you can pick any template you want)



Once the project is created, we will add an API controller



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": "abc@domain.com",

"SMTPPort": "5605"

}


My modified file looks like this




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 controller, 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;
}




The part you see in yellow is just a dummy method to get called when we run this API controller.

Now we are all setup 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 first method, we are getting our section from the configuration object. Inside this, we are getting another section that contains the value.

2) string dbConn2 = configuration.GetValue<string>("MySettings:DbConnection");

In second method, we are directly getting the string type value from configuration object. We are separating our nested sections by “:”.

So our modified controller will look something like this.





And below are the results of both methods.

Value from method 1


Value from method 2




So by 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 something 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; }
}




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 below code


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.





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




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;
 }




As you can see that appSettings.Value. is showing all our properties that are defined in our model.

Now when we run it you can see the values.





Summary

In this article, we have seen two approaches to read the values from 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.

43 views0 comments

© 2020 by Ravi.

  • Facebook Black Round
  • Twitter Black Round