我有一个.NET core 2.2 MVC项目,并且我想使用Configuration.Bind("the_key",object_instance)
从appsettings.json中读取数据(数组数据),但是它总是抛出错误“对象引用未设置为的实例”。一个对象”。
代码如下:
1.appsettings.json:
{
"Name": "pragram language",
"Items": [
{
"Language": "C#",
"Tool": "visual studio"
},
{
"Language": "JAVA",
"Tool": "Elcipse"
}
]
}
2。用appsettings.json映射的类:
public class MyClass
{
public String Name { get; set; }
public List<Item> Items { get; set; }
}
public class Item
{
public string Language { get; set; }
public string Tool { get; set; }
}
3。Startup.cs中的主要代码->配置方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//other code
app.Run(async context =>
{
var myclass = new MyClass();
//this does not work, and throw the error.
Configuration.Bind("Items", myclass);
//this code can work
//Configuration.Bind(myclass);
for (int i = 0; i < myclass.Items.Count; i++)
{
await context.Response.WriteAsync($"language is: {myclass.Items[i].Language}");
await context.Response.WriteAsync($"tool is: {myclass.Items[i].Tool}");
}
});
//other code
}
错误:
更新:
只需按照此issue找到解决方案,也许我对Bind方法不是很清楚:
app.Run(async context =>
{
List<Item> items = new List<Item>();
Configuration.Bind("Items", items);
for (int i = 0; i < items.Count; i++)
{
await context.Response.WriteAsync($"language is: {items[i].Language}");
await context.Response.WriteAsync($"tool is: {items[i].Tool}");
}
});