【发布时间】:2012-10-03 02:55:10
【问题描述】:
我的 web.config 中有一个自定义配置部分,如下所示:
<configSection>
<section name="CustomConfig" type="ConfigSectionRoot" allowLocation="true" allowDefinition="Everywhere"/>
</configSection>
<CustomConfig>
<ConfigRoot>
<add key="DataBase" value="CouchDB"/>
<add key="FrontEnd" value="Asp.Net"/>
<add key="AppName" value="Virtual WorkPlace"/>
</ConfigRoot>
</CustomConfig>
<AppSettings>
<add key="DataBase" value="CouchDB"/>
</AppSettings>
我的 ConfigSectionRoot.cs 是这样的:
public class ConfigSectionRoot:ConfigurationSection
{
[ConfigurationProperty("key", DefaultValue = "", IsKey = true, IsRequired = true)]
public string Key
{
get
{
return ((string)(base["key"]));
}
set
{
base["key"] = value;
}
}
[ConfigurationProperty("value", DefaultValue = "", IsKey = false, IsRequired = false)]
public string Value
{
get
{
return ((string)(base["value"]));
}
set
{
base["value"] = value;
}
}
}
如果我使用 AppSettings 而不是自定义配置,我可以像这样访问它:
string results= ConfigurationManager.AppSettings["Database"];
// results wil contain "CouchDB"
有没有什么方法可以在自定义配置部分实现同样的效果???请帮帮我
【问题讨论】:
-
您应该派生自 ConfigurationSection,而不是 ConfigurationElement。看看这个example。
-
@UfukHacıoğulları 我已更改,我可以访问它。但我的问题是我可以使用 AppSettings 中的键访问值吗
-
我不这么认为。 ConfigurationManager.AppSetting 可能会检查
中的元素 -
@UfukHacıoğulları 很好.. 有没有类似的东西.. 我们可以使用 CustomConfig.ConfigRoot["Database"] 之类的东西来获取值..
-
你可以在你的 ConfigSectionRoot 类中实现一个索引器。
标签: c# asp.net web-config custom-configuration