In previous article, I mentioned Read Values from appsettings.json in .NET Core Controller but now in this article, I have mentioned how you can read appsettings.json values in Program.cs in .NET Core 6+.

So let's create a new ASP.NET Core 6 or above project in Visual Studio 2022, by opening Visual Studio 2022 -> Select "Create new project" -> Select "ASP.NET Core Model View Controller" template and then name your project and in last step, select ".NET Core 6" as Framework.

Once Visual Studio generate template files, navigate to AppSettings.json and add some values.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  //added these values
  "Test": "Hello World",
  "settings": {
    "username": "guest",
    "password": "guest"
  }
}

Now, navigate to Program.cs, and to read above values in Program.cs you can use below code

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

System.Diagnostics.Debug.WriteLine(builder.Configuration["Test"]);

System.Diagnostics.Debug.WriteLine(builder.Configuration["settings:username"]);

and you will see "Output" as shown below in the image.

appsettings-json-asp-net-core-6-program-cs-configuration

So, complete program.cs file looks like below

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

//read values from appsettings.json
System.Diagnostics.Debug.WriteLine(builder.Configuration["Test"]);
//use ":" to read nested JSON values from appsettings
System.Diagnostics.Debug.WriteLine(builder.Configuration["settings:username"]);

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

That's it, hope this helps.

You may also like to read:

C# FromQuery Example in ASP.NET Core API

Format Code in Visual Studio (With Indentation)

Convert C# Class to JSON with Example