I know that there are tons of links about creating custom configuration sections out there, and tens of related questions has been asked here before. But I couldn’t solve my problem.
I’m able to create custom configuration sections, which are like:
<publicPaths>
<paths>
<add name="ProductServices" address="/services/productservices.asmx" />
<add name="LoginByToken" address="LoginByToken.ashx" />
</paths>
</publicPaths>
However, as you see, the meet of this configuration section (which is the items added to it) are at the 3rd nested level. In other words, you should traverse publicPaths -> paths -> add to get to the element representing the item. But what I want is a 2-level nesting, like:
<paths>
<add name="ProductServices" address="/services/productservices.asmx" />
<add name="LoginByToken" address="LoginByToken.ashx" />
</paths>
What should I do?
Update: The code of my 3-level custom configuration section is:
public class PublicPaths : ConfigurationSection
{
private static PublicPaths publicPaths = ConfigurationManager.GetSection("publicPaths") as PublicPaths;
public static PublicPaths Instance
{
get { return publicPaths; }
}
[ConfigurationProperty("paths", IsRequired = false)]
public PathCollection Paths
{
get { return this["paths"] as PathCollection; }
}
}
public class PathCollection : ConfigurationElementCollection
{
public Path this[int index]
{
get { return base.BaseGet(index) as Path; }
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
base.BaseAdd(index, value);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new Path();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((Path)element).Name;
}
}
public class Path : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("address", IsRequired = true)]
public string Address
{
get { return (string)this["address"]; }
set { this["address"] = value; }
}
}
You could try this code (it should work).
with this configuration
You could then access the values through