开发者

Problem creating custom configuration section in .config file

I have the following XML in my web.config

<mySectionGroup>

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

And the foll开发者_如何学编程owing code

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

And I get the following error when trying to retrieve that section

Unrecognized element 'page'. (C:\app\web.config line 39)

What am I missing here?


I suspect it will work with "add" rather than "page":

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

You have to do some extra work to customize the name of the "adder". At a minimum, you need to override AddElementName. If memory serves, there was something else, though - I just don't recall the specifics. I think it may be that you have to alter the collection type as well (override CollectionType).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜