I have a .Net Standard 2.0 Class Library and want to read config settings from .json file instead of .config.
Currently I read .config file as :
config = (CustomConfigSection)ConfigurationManager.GetSection(SectionName);
where CustomConfigSection is :
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;
}
}
and
public class CustomConfigElement: ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get => (string)this["value"];
set => this["value"] = value;
}
}
I was trying to do like :
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
But I am getting exception.
So I think, I need to implement not ConfigurationSection class but IConfigurationSection for CustomConfigSection class.