In this article I will explain with an example, how to read Connection String from AppSettings.json file inside Program.cs class in .Net Core 7 and ASP.Net Core 7.
 
 
Adding the AppSettings.json file
The following Connection String setting has been added in the AppSettings.json file.
{
 "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
 },
 "AllowedHosts": "*",
 "ConnectionStrings": {
    "MyConn": "Data Source=.\\SQL2022;Initial Catalog=Northwind;Integrated security=true"
 }
}
 
 
Reading Connection String from AppSettings.json file inside Program class
Inside the Program.cs file, the Connection String is read from the AppSettings.json file using the GetSection function of the Configuration property of the builder object.
var builder = WebApplication.CreateBuilder(args);
 
// Enabling MVC
builder.Services.AddControllersWithViews();
string conStr = builder.Configuration.GetSection("ConnectionStrings")["MyConn"];
 
var app = builder.Build();
 
//Configuring Routes
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
 
app.Run();
 
Screenshot
.Net Core 7: Read Connection String inside Program.cs from AppSettings.json file
 
 
Downloads


Other available versions