如何在 .net core 3.1 中使用 ConfigurationBulder 绑定到配置 class

How can I bind to a configuration class using ConfigurationBulder in .net core 3.1

我想使用 ConfigurationBuidler 来阅读我的 appsettings.json 文件。我看不出我做错了什么。

我的文件是

{
  "comment": "this gets copied to bin\debug on build. the app updates the copy. However to remember the settings you need to paste them here",
  "col1Width": "344"
}

我的测试失败

[TestMethod]
public void TestMethod1()
{
    var configuration = Helper.LoadConfiguration("appsettings.json");
    Assert.IsTrue(configuration.Properties.Keys.Contains("col1Width")); // fails here
}

我的帮手class是

public static  class Helper
{
    public static ConfigurationBuilder LoadConfiguration(string filename)
    {
        var configuration = new ConfigurationBuilder();
        var currentDirectory = System.IO.Directory.GetCurrentDirectory();
        configuration.SetBasePath(currentDirectory);
        configuration.AddJsonFile(path: filename, optional: false, reloadOnChange: true);
        configuration.Build();
        return configuration;
    }
}

[更新]

我根据博客 Post Marco 指出我更正了问题标题并更新了代码如下。

只有 .Bind 不可用

public static  class Helper
{
    public static FeedReadConfiguration GetApplicationConfiguration( )
    {
        var configuration = new FeedReadConfiguration();
        var currentDirectory = System.IO.Directory.GetCurrentDirectory();

        var iConfig = GetIConfigurationRoot(currentDirectory);

        iConfig
            .GetSection("FeedRead")
            .Bind(configuration); // Not available

        return configuration;
    }

    public static IConfigurationRoot GetIConfigurationRoot(string outputPath)
    {
        return new ConfigurationBuilder()
            .SetBasePath(outputPath)
            .AddJsonFile("appsettings.json")
            .Build();
    }

}
public class FeedReadConfiguration
{
    public int Col1Width { get; set; }
}

根据显示的设置文件,没有 "FeedRead" 部分

需要直接从根目录读取设置。

using Microsoft.Extensions.Configuration;

public static class Helper {
    public static FeedReadConfiguration GetApplicationConfiguration( ) {
        
        var currentDirectory = System.IO.Directory.GetCurrentDirectory();

        var iConfig = GetIConfigurationRoot(currentDirectory);

        //Microsoft.Extensions.Configuration.Binder.dll
        FeedReadConfiguration configuration = iConfig.Get<FeedReadConfiguration>();

        return configuration;
    }

    public static IConfiguration GetIConfigurationRoot(string outputPath) {
        return new ConfigurationBuilder()
            .SetBasePath(outputPath)
            .AddJsonFile("appsettings.json")
            .Build();
    }    
}

(需要Microsoft.Extensions.Configuration.Binder and Microsoft.Extensions.Configuration.Json

参考Configuration in ASP.NET Core

引用Options pattern in ASP.NET Core