如何从appsettings.json的根目录读取配置。

huangapple go评论57阅读模式
英文:

How to read configuration from root of appsettings.json

问题

我想为一个控制台.NET 7应用程序创建一个简单的appsettings.json文件,该文件包含在文件的根目录中的参数。
就像这样

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

如何在应用程序中读取这些参数并创建一个简单的结构,就像这样?

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

我使用了一个host,但之后呢?

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

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.???

答案1

得分: 1

这是一个供您选择的替代方案:

var builder = WebApplication.CreateBuilder(args);

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

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

如果您仍然想使用 Host.CreateApplicationBuilder(),则应该类似:

var builder = Host.CreateApplicationBuilder();

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

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

Settings 类:

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

Settings 文件 appsettings.json

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

Here is an alternative for you:

var builder = WebApplication.CreateBuilder(args);

builder.Services.Configure&lt;AppSettings&gt;(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&lt;AppSettings&gt;(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:

{
  &quot;Key1&quot;: 1,
  &quot;Key2&quot;: 2
}

huangapple
  • 本文由 发表于 2023年6月9日 06:00:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定