使用.NET Standard 2.0从JSON读取配置[重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

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

c# configuration .net-standard appsettings .net-standard-2.0
1个回答
0
投票

Thnx对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>();
© www.soinside.com 2019 - 2024. All rights reserved.