In this article I will explain with an example, how to read Connection String from AppSettings.json file in ASP.Net Core (.Net Core 8) Razor Pages.
What is IConfiguration
The IConfiguration is an interface for .Net Core Razor Pages.
The IConfiguration interface need to be injected as dependency in the PageModel and then later used throughout the PageModel.
The IConfiguration interface is used to read Settings and Connection Strings from AppSettings.json file.
Adding the AppSettings.json file
In order to add AppSettings.json file, right click on the Project in Solution Explorer. Then click Add, then New Item and then choose App Settings File option (shown below) and click Add button.
Once the file is created, we have to add Connection String.
Reading Connection String from AppSettings.json file using IConfiguration interface
In the below example, the IConfiguration is injected in the PageModel and assigned to the private property Configuration.
Then inside the PageModel, the Connection String is read from the AppSettings.json file using the GetSection function of the Configuration property.
public class IndexModel : PageModel
{
private IConfiguration Configuration;
public IndexModel(IConfiguration _configuration)
{
this.Configuration = _configuration;
}
public void OnGet()
{
string conString = this.Configuration.GetSection("ConnectionStrings")["ConString"];
}
}
Screenshot
Downloads