关于ConfigurationManager.GetSection()方法

111 篇文章 0 订阅
方法原型:
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
        }
    }
}








  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值