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。如何解决这个问题?

4

1 回答 1

26

您需要编写一个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");
于 2012-12-21T08:26:03.163 回答