In this article, we will see how to read values to configurations from the "appsettings.json" file in Asp.Net core. Nowadays, we create large applications, and not possible to load all data config data from the other sources but it is recommended to use configurations in the "appsetting.json" file.
We will use the "appsettings.json" file to store the configurations and also read those configurations using JsonConfigurationProvider
provided by Microsoft.
In many ways, we can retrieve values from the "appsettings.json" file in Asp.Net core,
I have added settings "WebsiteSettings" section in the appsettings.json file and added keys and values under that as shown below,
Appsettings.json :
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"WebsiteSettings": {
"Name": "Techieclues - A developer community website",
"Header": {
"MainBannerTitle": "Articles, Blogs and Q&As",
"HomePageSize": 25,
"RightSideMenu": true
}
},
"AllowedHosts": "*"
}
We will read only the "WebsiteSettings" section in the above appsettings.json file. We will access the section and bind them with strongly typed class using the Bind method. In order to Use Bind
method, we need to bind the class object instance to configuration values by matching property names against configuration keys recursively as shown below,
WebsiteSettings.cs:
namespace CoreAppSettingsExample.Models
{
public class WebsiteSettings
{
public string Name { get; set; }
public HeaderSettings Header { get; set; }
}
public class HeaderSettings
{
public string MainBannerTitle { get; set; }
public int HomePageSize { get; set; }
public bool RightSideMenu { get; set; }
}
}
The class name and properties should match with the appsetting.json section.
Code Snippet:
In the below code, we are retrieving and binding the "WebsiteSettings" section using Bind
method of IConfiguration.
using CoreAppSettingsExample.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
namespace CoreAppSettingsExample.Controllers
{
public class HomeController : Controller
{
private readonly IConfiguration configuration;
public HomeController(IConfiguration configuration)
{
this.configuration = configuration;
}
public IActionResult Index()
{
var websiteSettings = new WebsiteSettings();
// Retrieving and binding WebsiteSettings section using IConfiguration.
configuration.Bind("WebsiteSettings", websiteSettings);
// Serialize object
return Content(JsonConvert.SerializeObject(websiteSettings));
}
}
}
Comments (0)