Unrecognized configuration section

后端 未结 1 1435
日久生厌
日久生厌 2021-02-14 01:24

I have created a custom configuration section like below




    

        
相关标签:
1条回答
  • 2021-02-14 01:57

    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");
    
    0 讨论(0)
提交回复
热议问题