在web.config里自定义配置节
版本: 1.0
日期:2005-02-01
作者:[email protected]
说明:在web.config里自定义配置节,使用自定义的配置解析类
自定义配置节
配置文件是.NET Framework 定义的一组实现配置设置的标准的XML文件。web.config则是ASP.NET 程序的配置文件。
我们很容易就可以在web.config里增加自定义配置节。
1.在web.config里增加新的节点
msdn里的例子写的很清楚,要先写配置节的定义configSections。这个必须是<configuration>的第一个元素。
另外,type属性是配置解析类的类名(包括命名空间)和程序集名称。
这里用的是sysytem里已定义的NameValueSectionHandler。
<configuration>
<configSections>
<sectionGroup name="myGroup">
<sectionGroup name="nestedGroup">
<section name="mySection" type="System.Configuration.NameValueSectionHandler,System"/>
</sectionGroup>
</sectionGroup>
</configSections>
<myGroup>
<nestedGroup>
<mySection>
<add key="key_one" value="1"/>
<add key="key_two" value="2"/>
</mySection>
</nestedGroup>
</myGroup>
</configuration>
2.增加自定义的配置解析类
虽然framework已定义了几个配置解析类,但有时候我们要插入我们特定的解析方式,很简单,只要写一个类,实现IConfigurationSectionHandler接口即可。这个接口只有一个成员,读入的是相应的配置节,返回值即是我们用GetConfig得到的内容,也就是说,我们想通过这些配置,得到什么返回结果,在这里写就可以了。
Create | 由所有配置节处理程序实现,以分析配置节的 XML。返回的对象被添加到配置集合中,并通过 GetConfig 访问。 |
下面是一个简单的例子:
public class SpecialSectionHandler : IConfigurationSectionHandler
{
public virtual object Create(object parent, object context, XmlNode section)
{
Hashtable htResult = new Hashtable();
for(int i=0;i<section.ChildNodes.Count;i++)
{
XmlNode node = section.ChildNodes[i];
htResult[node.Attributes[KeyAttributeName].Value] = "I am a good guy ,and the value is "+Convert.ToString(node.Attributes[ValueAttributeName].Value);
}
return htResult;
}
public string KeyAttributeName
{
get
{
return "key";
}
}
public string ValueAttributeName
{
get
{
return "value";
}
}
如何使用自定义的解析类呢?在type里填上这个类的相关信息即可。类型名和程序集名。
<section name="mySection" type="WebApplication1.SpecialSectionHandler,WebApplication1"/>