我的任务是通过创建<configSection>
扩展我们应用的App.config,我们在其中定义Xml中相对复杂的对象。配置如下所示:
<configuration>
<appSettings>
<add key="MinWaitTime" value="150" />
<add key="MaxWaitTime" value="900" />
</appSettings>
<configSections>
<section name="clientconfig" type="KeepWarm.ClientConfig" />
</configSections>
<clientconfig username="test user" password="test password">
<urls>
<add url="test1" />
<add url="test2" />
<add url="test3" />
</urls>
</clientconfig>
</configuration>
最终,我必须能够定义多个<clientconfig>
,但我已经在努力只让一个人工作。
namespace KeepWarm
{
public class ClientConfig : ConfigurationSection
{
[ConfigurationProperty("username", IsRequired = true)]
public string UserName
{
get { return (string)base["username"]; }
set { base["username"] = value; }
}
[ConfigurationProperty("password", IsRequired = true)]
public string Password
{
get { return (string)base["password"]; }
set { base["password"] = value; }
}
[ConfigurationProperty("urls", IsRequired = true)]
public UrlCollection Urls
{
get { return (UrlCollection)base["urls"]; }
set { base["urls"] = value; }
}
}
[ConfigurationCollection(typeof(UrlElement))]
public class UrlCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new UrlElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((UrlElement)element).Url;
}
}
public class UrlElement : ConfigurationElement
{
[ConfigurationProperty("url", IsKey = true, IsRequired = true)]
public string Url
{
get { return (string)this["url"]; }
set { base["url"] = value; }
}
}
}
然而每当我尝试访问我的设置时,就像这样:
var minWaitTime = int.Parse(ConfigurationManager.AppSettings["MinWaitTime"]);
我得到System.Configuration.ConfigurationErrorsException
。
我一直在网上查看各种示例,但在我的案例中似乎没有任何帮助。我做错了什么?
答案 0 :(得分:1)
您的问题是声明配置部分的位置。 configSections标记需要紧跟在配置节点之后。试试这个:
<configuration>
<configSections>
<section name="clientconfig" type="KeepWarm.ClientConfig" />
</configSections>
<appSettings>
<add key="MinWaitTime" value="150" />
<add key="MaxWaitTime" value="900" />
</appSettings>
<clientconfig username="test user" password="test password">
<urls>
<add url="test1" />
<add url="test2" />
<add url="test3" />
</urls>
</clientconfig>
</configuration>