未识别的配置部分

12

我已经创建了一个自定义配置节,如下所示

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

自定义配置节处理程序

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;
            }
        }
    }
}

运行应用程序时抛出异常 Unrecognized configuration section Tabs。如何解决?


你能展示一下你的sectionGroup配置吗? - dove
你的 configSections 中有关于选项卡的任何内容吗? - dove
我已经添加了这样的代码:<section name="Tabs" type="EDaaS.Web.Helper.CustomConfigurationHandler, EDaaS.Web"/>。 - Jameel Moideen
1个回答

27
你需要编写一个配置处理程序来解析此自定义部分。然后在您的配置文件中注册此自定义处理程序。 configuration handler
<configSections>
    <section name="mySection" type="MyNamespace.MySection, MyAssembly" />
</configSections>

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

现在让我们定义相应的配置部分:
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"]; }
    }
}

现在,您可以访问设置:

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

我已经在配置部分添加了一个类似于以下的部分:<section name="Tabs" type="EDaaS.Web.Helper.CustomConfigurationHandler, EDaaS.Web"/>。 - Jameel Moideen
我遇到了运行时异常。 - Jameel Moideen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接