By Yuvaraj Shanmugam

Different ways to access AppSettings.json configuration in ASP.Net Core

In ASP.NET core reading of configuration is different from the previous versions (MVC 5 or lower versions) of ASP.NET. Since the configuration in ASP.NET core is in json format instead of the xml format in older versions.

I have created a sample application. In the appsettings.json there will be default settings created for logging and allowed hosts. I have added project settings in the configuration as shown below.

Now lets see the different ways we can access the settings.

In order to access the appsettings.json in our controller we need to inject the IConfiguration into the controller. In the below code I have injected the IConfiguration in the HomeController.

Now we have configuration in our controller. Lets see the first method to get a configuration value.

In order to access the settings in the configuration we can use the GetSection method. By using multiple GetSection’s we can navigate to get the child values. We then use the Value property to get the actual value as shown below in the example.

In above example we would always get the return value as string. Instead if we need to get the value with the exact type we can use GetValue<T> instead of the last GetSection like the below example. Here there is no Value property like the previous example.

In the above methods we are retrieving the configuration using multiple GetSection methods. This can reduced and the configuration can be read directly with only the GetValue<T>. The json keys can be seperated using colon as shown below.

The next method of reading configuration is through binding the json configuration with POCO class. For our example I am going to create a C# class that matches the json schema. Below is the class I have created. Since we require only Project Settings from the configuration I have only created ProjectSettings class and its subclass ImageSettings.

In controller now can bind this ProjectSettings class with the json schema using the Bind Function in GetSection method as shown below

I hope you found this post useful. Please do leave your comments.

Leave a Reply

Your email address will not be published. Required fields are marked *