Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read configuration from root of appsettings.json

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading