How to Read Values From appsettings.json In ASP.Net Core

  • Oct 24, 2021
  • 1
  • 286

How to Read values from appsettings.json in ASP.Net Core?

Answers (1)
Answer Accepted

We will use the "appsettings.json" file to store the configurations and also read those configurations using JsonConfigurationProvider provided by Microsoft. 

Sample appsettings.json file:

"WebsiteSettings": {
    "Name": "Techieclues - A developer community website",
    "Header": {
      "MainBannerTitle": "Articles, Blogs and Q&As",
      "HomePageSize": 25,
      "RightSideMenu": true
    }
  }

WebsiteSettings.cs:

The class name and properties should match with the appsetting.json section.

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

Using Bind method of IConfiguration, we can easily get the values from the appsettings.json file.

var websiteSettings = new WebsiteSettings();
// Retrieving and binding WebsiteSettings section using IConfiguration.  
configuration.Bind("WebsiteSettings", websiteSettings);
// Serialize object
return Content(JsonConvert.SerializeObject(websiteSettings));

If you want to more details, please see our article, Getting Values From appsettings.json File In ASP.Net Core.

Submit your answer