0

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:

enter image description here

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}");
            }
        });
Ivan Yang
  • 29,072
  • 2
  • 13
  • 31
  • @SᴇM, thanks, I will take a look:). – Ivan Yang Mar 19 '20 at 05:13
  • no problem, check either `myclass` or `Items`, one of them is `null`. – SᴇM Mar 19 '20 at 05:14
  • @SᴇM, yes, I'm pretty sure `Items` is null, but don't know how to fix it as of now. I will check the article and let you know if it can solve the issue. – Ivan Yang Mar 19 '20 at 05:15
  • @SᴇM, this can fix the "exception" if I follow the doc and initialize the both class instance with not null value. But after that, it will not read data from appsettings.json, just read the data I used to initialize the instance. – Ivan Yang Mar 19 '20 at 05:41
  • So your `Items` are `null`, because you couldn't read data from `appsettings.json`? – SᴇM Mar 19 '20 at 05:49
  • @SᴇM, you can see the answer in the update section. – Ivan Yang Mar 19 '20 at 05:55

0 Answers0