首页 > 解决方案 > 使用 .NET Standard 2.0 从 JSON 读取配置

问题描述

我有一个 .Net Standard 2.0 类库,想从 .json 文件而不是 .config 读取配置设置。

目前我将 .config 文件读取为:

config = (CustomConfigSection)ConfigurationManager.GetSection(SectionName);

其中 CustomConfigSection 是:

public class CustomConfigSection : ConfigurationSection
{
    [ConfigurationProperty("url")]
    public CustomConfigElement Url
    {
        get => (CustomConfigElement)this["url"];
        set => this["url"] = value;
    }

    [ConfigurationProperty("Id")]
    public CustomConfigElement Id
    {
        get => (CustomConfigElement)this["Id"];
        set => this["Id"] = value;
    }
}

public class CustomConfigElement: ConfigurationElement
{
    [ConfigurationProperty("value", IsRequired = true)]
    public string Value
    {
        get => (string)this["value"];
        set => this["value"] = value;
    }
}

我试图这样做:

var configBuilder = new ConfigurationBuilder().
SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("settings.json", optional: true, reloadOnChange: true)
.Build();

_config = (CustomConfigSection) configBuilder.GetSection(SectionName);
 // Exception due to casting to inappropriate class

但我得到了例外。

所以我认为,我需要为 CustomConfigSection 类实现不是 ConfigurationSection 类而是 IConfigurationSection。

标签: c#configuration.net-standardappsettings.net-standard-2.0

解决方案


感谢 Zysce发表评论。所以我就是这样做的,而且效果很好。

在这里,我将 CustomConfigSection 类更改为:

public class CustomConfigSection
{
  public CustomConfigElement Url {get; set;}
  public CustomConfigElement Id {get; set;}
}

并将 Json 配置读取为:

Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

var configBuilder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json", optional: true, reloadOnChange: true)
            .Build();

_config = configBuilder.GetSection(SectionName).Get<CustomConfigSection>();

推荐阅读