在 dotnet 核心中,对 config.GetSection().Get <List<object>> 的调用不会将值加载到对象中

In dotnet core the call to config.GetSection().Get <List<object>> will not load values into the object

在我的 appsetting.json 中,我定义了以下值数组。

"DirectoriesToMonitor": [
  {
    "DirectoryToMonitor": {
      "Directory": "c:\temp1",
      "IncludeSubDirectories": true,
      "FileTypes": "txt",
      "ZipFiles": false,
      "NotifyOnly": true
    }
  },
  {
    "DirectoryToMonitor": {
      "Directory": "c:\temp2",
      "FileTypes": "txt",
      "ZipFiles": false,
      "NotifyOnly": true
    }
  }
]

我正在尝试使用此语句将它们加载到对象列表中。

List<DirectoryToMonitor> dirs = config.GetSection("DirectoriesToMonitor").Get<List<DirectoryToMonitor>>();

"dirs" 列表填充了 2 个对象,但每个对象的属性未从 appsettings 加载。

我也试过这个:

List<DirectoryToMonitor> directories = new List<DirectoryToMonitor>();
config.Bind("DirectoriesToMonitor", directories);

我得到了相同的结果。

namespace FileWatcherEmailer
{
    public class DirectoryToMonitor
    {
        public string Directory { get; set; }
        public bool IncludeSubDirectories { get; set; }
        public string FileTypes { get; set; }
        public bool ZipFiles { get; set; }
        public bool NotifyOnly { get; set; }
    }
}

DirectoryToMonitor 对象 不匹配 JSON 文件。该文件包含具有单个 属性 的对象数组,该数组又包含与 DirectoryToMonitor class.

匹配的属性

JSON 文件中的 "DirectoryToMonitor" 字符串指定了一个字段,而不是对象类型。 JSON 没有类型,任何 JSON 反序列化器都会将 JSON 片段反序列化为与其内容匹配的任何类型。

要使您的代码正常工作,JSON 文件应如下所示:

"DirectoriesToMonitor": [
  {
    "Directory": "c:\temp1",
    "IncludeSubDirectories": true,
    "FileTypes": "txt",
    "ZipFiles": false,
    "NotifyOnly": true
  },{
    "Directory": "c:\temp2",
    "FileTypes": "txt",
    "ZipFiles": false,
    "NotifyOnly": true
  }
]

如果你想保持文件不变,你需要使用一个新的class和一个DirectoryToMonitor属性,持有一个DirectoryToMonitor对象:

class DirectoryToMonitorDTO 
{
    public DirectoryToMonitor DirectoryToMonitor {get; set;}
}

代码必须更改为:

List<DirectoryToMonitor> directories =
    config.GetSection("DirectoriesToMonitor")
          .Get<List<DirectoryToMonitorDTO>>()
          .Select(dto=>dto.DirectoryToMonitor)
          .ToList();

您必须将 Base class 更改为此

public class DirectoryToMonitor
{
    public string Directory { get; set; }
    public bool IncludeSubDirectories { get; set; }
    public string FileTypes { get; set; }
    public bool ZipFiles { get; set; }
    public bool NotifyOnly { get; set; }
}

public class DirectoriesToMonitor
{
    public DirectoryToMonitor DirectoryToMonitor { get; set; }
}

public class RootObject
{
    public List<DirectoriesToMonitor> DirectoriesToMonitor { get; set; }
}

最后将 json 绑定到 List<DirectoriesToMonitor>

List<DirectoriesToMonitor> directories = new List<DirectoriesToMonitor>();
config.GetSection("DirectoriesToMonitor").Bind(directories);

List<DirectoriesToMonitor> directories = new List<DirectoriesToMonitor>();
config.Bind("DirectoriesToMonitor", directories);