C# 读取屏幕上appsetting.json文件中的所有数组值,并读取id=555的书籍信息
在appsettings.json中C# 读取屏幕上appsetting.json文件中的所有数组值,并读取id=555的书籍信息,c#,asp.net-core,C#,Asp.net Core,在appsettings.json中 { "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information"
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"book": [
{
"id": "555",
"language": "C",
"edition": "First",
"author": "Dennis Ritchie "
},
{
"id": "666",
"language": "C#",
"edition": "Second",
"author": "Anders Hejlsberg"
}
]
}
在Startup.cs中,我只通过索引获取一个值,下面是我通过id获取的值
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync(Configuration.GetSection("book:0:id").Value);
});
}
上面有我的代码,我只得到一个值,如何得到所有数组?
谢谢 您可以尝试以下方法:
var list = new List<MyBookClass>();
Configuration.GetSection("book").Bind(list);
foreach(var book in list)
{
//do what ever you want with your list of books
}
public class MyBookClass
{
public string id { get; set; }
public string language { get; set; }
public string edition { get; set; }
public string author { get; set; }
}
这是在asp.net core中读取设置的常见模式
然后你可以对列表做任何你想做的事情