探秘web.config之自定义配置节点
0. web.config文档中,各个节点的属性如何设置可以参考《configuration Element (General Settings Schema)》一文及其中的Reference小节。
1. 往web.config中写入自定义的配置节点(configuration section),就必须顺带地实现该自定义配置节点的操作类(configuration section handler)。
在.net2.0以前,操作类必须实现
System.Configuration.IConfigurationSectionHandler
接口。
2. 现在,操作类必须继承System.Configuration.ConfigurationSection 类,并和特性结合起来。在操作类和web.config的配置节点之间建立起映射。
操作类的属性和配置节的属性通过ConfigurationProperty特性建立起映射。
3. 例如在web.config中添加新节点<myCustomSection myAttrib1="Clowns">,则可创建类MyHandler,并有一个属性myAttrib1。定义如下:
public class MyHandler : ConfigurationSection
{
public MyHandler()
{
}
public MyHandler(String attribVal)
{
MyAttrib1 = attribVal;
}
//通过特性建立映射
[ConfigurationProperty("myAttrib1", DefaultValue = "Clowns", IsRequired = true)]
public String MyAttrib1
{
get
{ return (String)this["myAttrib1"]; }
set
{ this["myAttrib1"] = value; }
}
}
4.
在web.config中除了新增自定义配置节点外,还要在<configSections>节点内添加一个<section>节点,用以声明操作类节点。上述例子中可以添加:
<section
name="myCustomSection"
type="MyConfigSectionHandler.MyHandler"
allowLocation="true"
allowDefinition="Everywhere"
/>
至于section节点的属性如何设置,参见《section Element for configSections (General Settings Schema)》
5. 如何读或写该节点呢?
只需要ConfigurationManager的GetSection方法,创建一个MyHandler对象!接下来就可以像操作一般对象那样操作它了。
protected void Button1_Click(object sender,
EventArgs e)
{
MyConfigSectionHandler.MyHandler config
=
(MyConfigSectionHandler.MyHandler)System.Configuration.ConfigurationManager.GetSection(
"myCustomSection");
Response.Write(config.MyAttrib1.ToString());
}
6. 参考文献:
[1]《How to: Create Custom Configuration Sections Using
ConfigurationSection》
[2]《在Web.config配置文件中自定义配置节点(转载)》
[3]《Web.config自定义节点configSections》
注:[3]的实现方法已经过时。

浙公网安备 33010602011771号