Configuration.GetSection从appsetting.json获取值,但是Configuration.GetSection.Bind始终返回null

问题描述

我在下面的代码中尝试将我的appsettings.json与我的变量绑定,并且我的变量属于类类型,其模型已根据JSON模式进行了适当定义。

在调试过程中,可以快速查看config.GetSection("TableStorageRule") appsettings.json 的值,但对于config.GetSection("TableStorageRule").Bind(tableStorageOutput),其 null

var builder = new ConfigurationBuilder()
        .SetBasePath(Path.Combine(Root))
        .AddJsonFile("appsettings.json",optional: false);

var config = builder.Build();

var tableStorageOutput = new TableStorageRule();            
config.GetSection("TableStorageRule").Bind(tableStorageOutput);
var nameOfFilter = tableStorageOutput.Name;

我想知道我在做什么错?

这是我的模型类定义

public class TableStoreSettings
{
    public class AzureTableSettings
    {
        public string Account { get; set; }
        public string Key { get; set; }
        public string Table { get; set; }
    }

    public AzureTableSettings AzureTable { get; set; }

    public Uri SchemaBaseUri { get; set; }
}

public class TableStorageRule
{
    public string Name { get; set; }
    public TwisterDataFilter DataFilter { get; set; }
    public TableStoreSettings TableSettings { get; set; }
}

这是我的Json模式>

{  "TableStorageRule": [
  {
    "Name": "filterRule1","DataFilter": {
      "DataSetType": "Settings1"
    
    },"TableStoreSettings": {
      "AzureTable": {
        "Account": "account1","Table": "table1","Key": "key1"
      },"SchemaBaseUri": "https://test.web.core.windows.net/"
    }
  } 
]}

解决方法

问题出在您的Json。需要将TableStoreSettings重命名为TableSettings以匹配该类,并且您的TableStorageRule不是规则数组。

{
  "TableStorageRule": {
    "Name": "filterRule1","DataFilter": {
      "DataSetType": "Settings1"

    },"TableSettings": {
      "AzureTable": {
        "Account": "account1","Table": "table1","Key": "key1"
      },"SchemaBaseUri": "https://test.web.core.windows.net/"
    }
  }
  
}

如果您打算使用一系列规则,建议您再放置一个Top Level类。

    public class TableStorageRules
    {
        public List<TableStorageRule> Rules { get; set; }
    }

然后您的Json看起来像这样

{
  "TableStorageRule": {
    "Rules": [
      
      {
        "Name": "filterRule1","DataFilter":
        {
          "DataSetType": "Settings1"

        },"TableSettings":
        {
          "AzureTable": {
            "Account": "account1","Key": "key1"
          },"SchemaBaseUri": "https://test.web.core.windows.net/"
        }

      }
    ]
  }

}

对于Bind,您将使用此

        var builder = new ConfigurationBuilder()
                        .SetBasePath(Path.Combine(Root))
                        .AddJsonFile("appsettings.json",optional: false);

        var config = builder.Build();

        var tableStorageOutput = new TableStorageRules();
        config.GetSection("TableStorageRule").Bind(tableStorageOutput);
        var nameOfFilter = tableStorageOutput.Rules[0].Name;