使用.NET Standard 2.0从JSON读取配置

时间:2018-08-27 15:03:08

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

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

但是我要例外了。

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

1 个答案:

答案 0 :(得分: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>();