Unrecognized configuration section

笑着哭i 提交于 2021-02-06 20:44:11

问题


I have created a custom configuration section like below

<configSections>
</configSections>
<Tabs>
    <Tab name="Dashboard" visibility="true" />
    <Tab name="VirtualMachineRequest" visibility="true" />
    <Tab name="SoftwareRequest" visibility="true" />
</Tabs>

Custom Configuration Section Handler

namespace EDaaS.Web.Helper
{
    public class CustomConfigurationHandler : ConfigurationSection
    {
        [ConfigurationProperty("visibility", DefaultValue = "true", IsRequired = false)]
        public Boolean Visibility
        {
            get
            {
                return (Boolean)this["visibility"];
            }
            set
            {
                this["visibility"] = value;
            }
        }
    }
}

While running the application throws exception Unrecognized configuration section Tabs. How to resolve this?


回答1:


You need to write a configuration handler to parse this custom section. And then register this custom handler in your config file:

<configSections>
    <section name="mySection" type="MyNamespace.MySection, MyAssembly" />
</configSections>

<mySection>
    <Tabs>
        <Tab name="one" visibility="true"/>
        <Tab name="two" visibility="true"/>
    </Tabs>
</mySection>

Now let's define the corresponding config section:

public class MySection : ConfigurationSection
{
    [ConfigurationProperty("Tabs", Options = ConfigurationPropertyOptions.IsRequired)]
    public TabsCollection Tabs
    {
        get
        {
            return (TabsCollection)this["Tabs"];
        }
    }
}

[ConfigurationCollection(typeof(TabElement), AddItemName = "Tab")]
public class TabsCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new TabElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }
        return ((TabElement)element).Name;
    }
}

public class TabElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true, IsKey = true)]
    public string Name
    {
        get { return (string)base["name"]; }
    }

    [ConfigurationProperty("visibility")]
    public bool Visibility
    {
        get { return (bool)base["visibility"]; }
    }
}

and now you could access the settings:

var mySection = (MySection)ConfigurationManager.GetSection("mySection");


来源:https://stackoverflow.com/questions/13985914/unrecognized-configuration-section

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!