本文转自:http://www.blue1000.com/bkhtml/2008-02/55810.htm

前几天写了一篇使用IConfigurationSectionHandler在web.config中增加自定义配置,然后看到有回复说IConfigurationSectionHandler在2.0时代被弃用了,推荐使用ConfigurationSection,不敢怠慢,赶紧看看ConfigurationSecion是如何使用的。
 
  1. 实现目的
      我希望在web.config中,配置网站信息,管理员信息,和用户信息(当然这个配置有点不切实际了,这里只是为了演示),所以,我希望按下面的格式做配置。
  <siteSetting siteName="遇见未来" siteVersion="1.0" closed="false">
      <siteAdmin adminId="1" adminName="guozhijian"/>
      <siteUsers>
        <siteUser userId="1" userName="zhanglanzhen"/>
        <siteUser userId="2" userName="wdy"/>
      </siteUsers>
    </siteSetting>     这个siteSetting配置节点是一个稍微复杂一点的配置,自己包含有Attributes,同时包含子节点siteAdmin, siteUsers, 而siteUsers又包含多个siteUser子节点。
      接下来我要定义几个类,分别代表各个不同的节点。有一定的规则:
      代表根节点,也就是siteSetting节点的类,继承自ConfigurationSection类
      代表单一子节点的siteAdmin, siteUser类,继承自ConfigurationElement类
      包含多个同名子节点的siteUsers类,继承自ConfigurationElementCollection类
  2. SiteAdmin类
       public class SiteAdmin : ConfigurationElement
      {
          [ConfigurationProperty("adminId", IsRequired=true)]
          public int AdminId {
              get { return Convert.ToInt32(this["adminId"]); }
              set { this["adminId"] = value; }
          }
          [ConfigurationProperty("adminName")]
          public string AdminName {
              get { return this["adminName"] as string; }
              set { this["adminName"] = value; }
          }
      }    注意ConfigurationPropertyAttribute,和this关键字,很明显在基类中定义了索引器。本文并不想对这些做过多探讨,直接以代码展示。
  3. SiteUser类
       public class SiteUser : ConfigurationElement {
 
          [ConfigurationProperty("userId",IsRequired=true)]
          public int UserId {
              get { return Convert.ToInt32(this["userId"]); }
              set { this["userId"] = value; }
          }
          [ConfigurationProperty("userName")]
          public string UserName {
              get { return this["userName"] as string; }
              set { this["userName"] = value; }
          }
      }
  4. SiteUsers类
  public class SiteUsers : ConfigurationElementCollection {
 
          protected override ConfigurationElement CreateNewElement() {
              return new SiteUser();
          }
 
          protected override object GetElementKey(ConfigurationElement element) {
              SiteUser siteUser = element as SiteUser;
              return siteUser.UserId;
          }
 
          public override ConfigurationElementCollectionType CollectionType {
              get {
                  return ConfigurationElementCollectionType.BasicMap;
              }
          }
          protected override string ElementName {
              get {
                  return "siteUser";
              }
          }
      }    继承自ConfigurationElementCollection的类,必须override以上4个方法。
      SiteUsers是SiteUser的集合,因此不难理解上述4个override方法的目的。
  5. SiteSetting类
  public class SiteSetting : ConfigurationSection {
         
          [ConfigurationProperty("siteName")]
          public string SiteName {
              get { return this["siteName"] as string; }
              set { this["siteName"] = value; }
          }
          [ConfigurationProperty("siteVersion")]
          public string SiteVersion {
              get { return this["siteVersion"] as string; }
              set { this["siteVersion"] = value; }
          }
          [ConfigurationProperty("closed", IsRequired=true)]
          public bool Closed {
              get { return (bool)this["closed"]; }
              set { this["closed"] = value; }
          }
 
          [ConfigurationProperty("siteAdmin")]
          public SiteAdmin SiteAdmin {
              get { return this["siteAdmin"] as SiteAdmin; }
              set { this["siteAdmin"] = value; }
          }
          [ConfigurationProperty("siteUsers")]
          public SiteUsers SiteUsers {
              get { return this["siteUsers"] as SiteUsers; }
          }
      }
  6. 在web.config添加我们的自定义配置
      根据我们最初的设想,现在来对web.config进行配置
      在<configSections></configSections>中加入:
       <section name="siteSetting" type="Tristan.SeeCustomCfg.SiteSetting"/>   
      在<configuration></configuration>中加入:
  <siteSetting siteName="遇见未来" siteVersion="1.0" closed="false">
      <siteAdmin adminId="1" adminName="guozhijian"/>
      <siteUsers>
        <siteUser userId="1" userName="zhanglanzhen"/>
        <siteUser userId="2" userName="wdy"/>
      </siteUsers>
    </siteSetting>
  7. 检验结果
      这样就完成了吗?是的。
      来写简单的测试代码,将我们的自定义配置信息输出来:
       public partial class _Default : System.Web.UI.Page {
          protected void Page_Load(object sender, EventArgs e) {
 
              SiteSetting siteSetting = ConfigurationManager.GetSection("siteSetting") as SiteSetting;
 
              Response.Write(siteSetting.SiteName + "," + siteSetting.SiteVersion + "," + siteSetting.Closed.ToString());
              Response.Write("<br/>");
 
              Response.Write(siteSetting.SiteAdmin.AdminId.ToString() + "," + siteSetting.SiteAdmin.AdminName);
              Response.Write("<br/>");
 
              foreach (SiteUser u in siteSetting.SiteUsers) {
                  Response.Write(u.UserId.ToString() + "," + u.UserName);
                  Response.Write("<br/>");
              }
          }
      }
      测试通过:)
     
      再联想之前使用IConfigurationSectionHandler,我觉得比本文描写的方法更好用,为什么?因为更容易理解啊,只需实现一个接口,不像这个,要根据不同的情况分别继承那么几个类。
      如果IConfigurationSectionHandler果真在2.0里不推荐使用,那么却又在3.5中恢复身份,也是可以理解的。

[转]通过继承ConfigurationSection,在web.config中增加自定义配置的更多相关文章

  1. 使用IConfigurationSectionHandler在web.config中增加自定义配置

    一. 场景    这里仅举一个简单应用的例子,我希望在web.config里面增加网站的基本信息,如:网站名称,网站版本号,是否将网站暂时关闭等.二. 基本实现方法1. 定义配置节点对应的类:Site ...

  2. 通过Web.config中的configSections配置自己系统的全局常量

    通过Web.config中的configSections配置自己系统的全局常量 随着系统的庞大,你的全局信息保存在appsitting里可能会比较乱,不如为模块写个自定义的全局常量吧 首先在Web.C ...

  3. 加密web.config中的邮件配置mailSettings

    加密: 在命令提示符下键入: aspnet_regiis -pef connectionStrings 要加密的web.config完整路经 演示样例:C:\Program Files (x86)\M ...

  4. 释放SQL Server占用的内存 .Net 读取xml UrlReWriter 在web.config中简单的配置

    释放SQL Server占用的内存   由于Sql Server对于系统内存的管理策略是有多少占多少,除非系统内存不够用了(大约到剩余内存为4M左右),Sql Server才会释放一点点内存.所以很多 ...

  5. App.config和Web.config配置文件的自定义配置节点

    前言 昨天修改代码发现了一个问题,由于自己要在WCF服务接口中添加了一个方法,那么在相应调用的地方进行更新服务就可以了,不料意外发生了,竟然无法更新.左查右查终于发现了问题.App.config配置文 ...

  6. ASP.NET,web.config 中SessionState的配置

    web Form 网页是基于HTTP的,它们没有状态, 这意味着它们不知道所有的请求是否来自同一台客户端计算机,网页是受到了破坏,以及是否得到了刷新,这样就可能造成信息的丢失. 于是, 状态管理就成了 ...

  7. web.config中namespace的配置(针对页面中引用)

    1,在页面中使用强类型时: @model GZUAboutModel @using Nop.Admin.Models//命名空间(注意以下) 2,可以将命名空间提到web.config配置文件中去,此 ...

  8. .Net高级编程-自定义错误页 web.config中<customErrors>节点配置

    错误页 1.当页面发生错误的时候,ASP.Net会将错误信息展示出来(Sqlconnection的错误就能暴露连接字符串),这样一来不好看,二来泄露网站的内部实现信息,给网站带来安全隐患,因此需要定制 ...

  9. spring中增加自定义配置支持

    spring.schemas 在使用spring时,我们会首先编写spring的配置文件,在配置文件中,我们除了使用基本的命名空间http://www.springframework.org/sche ...

随机推荐

  1. UVALive 7267 Mysterious Antiques in Sackler Museum (判断长方形)

    Sackler Museum of Art and Archaeology at Peking University is located on a beautiful site near the W ...

  2. 岛屿(洛谷 U5399)

    题目背景 放假了,Lkw和mm到岛上旅游.阳光明媚,风景秀丽.正当Lkw和mm享受眼前这旖旎的风光时,突降大雨,小岛上开始积水,没过几分钟,水便快要触及膝盖.Lkw和mm意识到了事态的严重性,赶紧向高 ...

  3. 水果姐逛水果街Ⅰ(codevs 3304)

    题目描述 Description 水果姐今天心情不错,来到了水果街. 水果街有n家水果店,呈直线结构,编号为1~n,每家店能买水果也能卖水果,并且同一家店卖与买的价格一样. 学过oi的水果姐迅速发现了 ...

  4. Struts2中过滤器和拦截器的区别

    拦截器和过滤器的区别: 1.拦截器是基于java的反射机制的,而过滤器是基于函数回调 2.过滤器依赖与servlet容器,而拦截器不依赖与servlet容器 3.拦截器只能对action请求起作用,而 ...

  5. canvas 在线画图

    canvas 在线画图 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...

  6. struts2的标签中得到JSP脚本的变量值

    转自:http://www.cnblogs.com/modou/articles/1299024.html 大家先来看一段代码: <% int i=1; %> <s:property ...

  7. 【bzoj1066】[SCOI2007]蜥蜴 网络最大流

    [bzoj1066][SCOI2007]蜥蜴 Description 在一个r行c列的网格地图中有一些高度不同的石柱,一些石柱上站着一些蜥蜴,你的任务是让尽量多的蜥蜴逃到边界外. 每行每列中相邻石柱的 ...

  8. 详细剖析电脑hosts文件的作用和修改

    提到电脑系统中的hosts文件,如果不是太熟悉的话,还真是闻所未闻,一是由于系统的hosts文件为系统属性,在系统默认设置下,我们根本无法看到它的存在,而是由于身处系统深层文件夹内,我们一般也无法察觉 ...

  9. thinkphp where()条件查询

    今天来给大家讲下查询最常用但也是最复杂的where方法,where方法也属于模型类的连贯操作方法之一,主要用于查询和操作条件的设置.where方法的用法是ThinkPHP查询语言的精髓,也是Think ...

  10. 自定义漂亮的Android SeekBar样式

    系统自带的SeekBar真是太难看了,不能容忍! 只能自己做了,先来张效果图 第1个Seekbar 背景是颜色,thumb是图片,上代码: <SeekBar android:id="@ ...