How to read configuration from root of appsettings.json

Advertisements

I want to have a simple appsettings.json for a console .NET 7 application with parameters in the root of the file.
Like this

{
  "Key1": 1,
  "Key2": 2
}

How to read this in the application into a simple structure like this?

public struct Settings
{
   public required int Key1 { get; set; }
   public required int Key2 { get; set; }
}

I use a host, but what then?

var host = Host.CreateApplicationBuilder();
var config = host.Configuration.???

>Solution :

Here is an alternative for you:

var builder = WebApplication.CreateBuilder(args);

builder.Services.Configure<AppSettings>(builder.Configuration);

var app = builder.Build();
app.Run();

If you still want to use Host.CreateApplicationBuilder() should be similar:

var builder = Host.CreateApplicationBuilder();

builder.Services.Configure<AppSettings>(builder.Configuration);

var host = builder.Build();
host.Run();

Settings class:

public class AppSettings
{
    public int Key1 { get; set; }
    public int Key2 { get; set; }
}

Settings file appsettings.json:

{
  "Key1": 1,
  "Key2": 2
}

Leave a ReplyCancel reply