I have a .NET core 2.2 MVC project, and I want to use Configuration.Bind("the_key",object_instance)
to read data(array data) from appsettings.json, but it always throw the error "object reference not set to an instance of an object".
The code is as below:
1.appsettings.json:
{
"Name": "pragram language",
"Items": [
{
"Language": "C#",
"Tool": "visual studio"
},
{
"Language": "JAVA",
"Tool": "Elcipse"
}
]
}
2.The classes mapped with 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.The main code in Startup.cs -> Configure method:
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
}
The error:
update:
Just find a solution as per this issue, maybe I'm not very clear about the Bind method:
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}");
}
});