本文转自: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. 项目总结(五)--- 界面调试工具Reveal

    在开发中,我们也许会碰到以下需求:对于一些动态复杂的交互界面,手码去制定界面是常有的事情,然而我们在开发中想修改过一些参数后想看下实时效果,只能重新运行项目,进入到对应的页面来进行修改,是不是有点麻烦 ...

  2. Intellj IDEA快捷键

    Alt+回车 导入包,自动修正 Ctrl+N   查找类 Ctrl+Shift+N 查找文件 Ctrl+Alt+L  格式化代码 Ctrl+Alt+O 优化导入的类和包 Alt+Insert 生成代码 ...

  3. surface RT app安装心得

    打开store,然后在键盘输入字母,就出现搜索栏了. 想安装qq,但是输入后找不到软件,原因是我在初始化系统的时候,我的所在地选择的是新加坡,因此找不到软件.在屏幕右下方的setting,然后将所在地 ...

  4. 组合数(codevs 1631)

    1631 组合数  时间限制: 1 s  空间限制: 256000 KB  题目等级 : 钻石 Diamond 题解  查看运行结果     题目描述 Description 组合数C(N, K)表示 ...

  5. Redis经验谈

    新浪作为全世界最大的Redis用户,在开发和运维方面有非常多的经验.本文作者来自新浪,希望能为业界提供一些亲身经历,让大家少走弯路. 使用初衷 从2010年上半年起,我们就开始尝试使用Redis,主要 ...

  6. 利用Roslyn把C#代码编译到内存中并进行执行

    Tugberk Ugurlu在其博文<Compiling C# Code Into Memory and Executing It with Roslyn>中给大家介绍了一种使用.NET下 ...

  7. 获取表信息(MSSQL)

    涉及到的系统表汇总 sys.databases sys.objects sys.indexes sys.tables sys.columns sys.data_spaces sys.partition ...

  8. Spark metrics on wordcount example

    I read the section Metrics on spark website. I wish to try it on the wordcount example, I can't make ...

  9. 【spring 区别】ClassXmlAplicationContext和FileSystemXmlApplicationContext的区别

    今天写一个简单的spring使用例子,遇到这个问题: 项目结构如下: 代码如下: package com.it.sxd; import java.nio.file.FileSystem; import ...

  10. Hark的数据结构与算法练习之圈排序

    算法说明 圈排序是选择排序的一种.其实感觉和快排有一点点像,但根本不同之处就是丫的移动的是当前数字,而不像快排一样移动的是其它数字.根据比较移动到不需要移动时,就代表一圈结束.最终要进行n-1圈的比较 ...