使用Configuration.Bind方法从appsettings.json读取数组数据时发生错误“对象引用未设置为对象的实例”

问题描述 投票:0回答:1

我有一个.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
    }

错误:

enter image description here

c# asp.net-core-mvc asp.net-core-2.2
1个回答
0
投票

我找到了解决方案:

        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}");
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.