这个问题在这里已有答案:
我有一个.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。
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>();