在.config文件中创建自定义配置部分时出现问题

时间:2010-08-15 19:01:20

标签: c# configuration

我的web.config中有以下XML

<mySectionGroup>

        <sectionOneSection>
            <page path="~/123.aspx"></page>
            <page path="~/456.aspx"></page>
        </sectionOneSection>
    </mySectionGroup>

以下代码

public class SectionOneSection : ConfigurationSection {

    [ConfigurationProperty("sectionOne")]
    public PageConfigurationCollection Pages {

        get {
            return this["sectionOne"] as PageConfigurationCollection;
        }
    }

    public static SectionOneSection GetConfig() {

        return ConfigurationManager.GetSection("mySectionGroup/sectionOneSection") as
                SectionOneSection;
    }
}

public class PageElement : ConfigurationElement {

    [ConfigurationProperty("path", IsRequired = true)]
    public string Path {

        get {

            return this["path"].ToString();
        }

        set {
            this["path"] = value;
        }
    }
}

public class PageConfigurationCollection : ConfigurationElementCollection {

    public PageElement this[int index] {

        get {

            return base.BaseGet(index) as PageElement;
        }

        set {

            if (base.BaseGet(index) != null) {
                base.BaseRemoveAt(index);
            }
            this.BaseAdd(index, value);
        }
    }

    protected override string ElementName {
        get {
            return base.ElementName;
        }
    }

    protected override ConfigurationElement CreateNewElement() {
        return new PageElement();
    }

    protected override object GetElementKey(ConfigurationElement element) {
        return ((PageElement)element).Path;
    }
}

尝试检索该部分时出现以下错误

无法识别的元素'page'。 (C:\ app \ web.config第39行)

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

我怀疑它可以使用“添加”而不是“页面”:

<mySectionGroup>
    <sectionOneSection>
        <add path="~/123.aspx"/>
        <add path="~/456.aspx"/>
    </sectionOneSection>
</mySectionGroup>

您必须做一些额外的工作来自定义“加法器”的名称。至少,您需要覆盖AddElementName。如果记忆服务,那么还有其他东西 - 我只是不记得具体细节。我认为你可能也需要改变集合类型(覆盖CollectionType)。