1

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.

0

1 Answer 1

0

Thnx to Zysce for comment. So that's how I did and it works good.

Here I change CustomConfigSection class like :

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

And read Json config as :

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>();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.