public static object GetSection(string sectionName);
其中sectionName:配置节的路径和名称。
返回结果:指定的 System.Configuration.ConfigurationSection 对象,或者,如果该节不存在,则为 null。
注意,GetSection方法读取的是configSections节点,这个节点在web.config配置文件中,它比较特殊,必须放置于首节点,也就是说,在它之前不能有其它类型的节点。configSections子节点有section和sectionGroup,后者是前者的集合节点,比如:
<sectionGroup name="urlRewrite">
<section name="rules" type="Web.UI.RuleProviderHandler"/>
</sectionGroup>
sectionGroup可以配置多个,可根据name属性来分类。下面说说它的作用,通过对ConfigurationManager.GetSection(...)方法的调用,如果某个类继承IConfigurationSectionHandler接口,那么会触发此接口的Create方法,这样我们就可以做一些事了。下面以一个url重写的例子来说明:
添加节点:
我们根据configSections节点,用ConfigurationManager.GetSection读取name=“urlRewrite”的section的type,也就是Web.UI.RuleProviderHandler,对它进行显示转化:
假如我们已经写好一个类就是RuleProviderHandler.cs(它的命名空间正好就是namespace Web.UI),我们让这个类继承于IConfigurationSectionHandler。
那么,
xxxxxconf = (xxxxx)ConfigurationManager.GetSection("urlRewrite/rules");
便会触发Create方法
using System.Configuration;
using System.Xml;
namespace Web.UI
{
public class RuleProviderHandler : IConfigurationSectionHandler
{
public RuleProviderHandler() { }
public object Create(object parent, object configContext, XmlNode section)
{
//do something
}
}
}