英文:
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<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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论