我们通常把诸如sql的connection string之类的配置信息保存在web.config的AppSettings部分,以方便程序的分发,并且可以通过以下方法在程序中获得:
string sqlStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];

对于结构比较复杂的自定义配置,可以通过实现IConfigurationSectionHandler接口来实现这种机制。首先,创建MySettings类,该类仅包含了我需要的一些自定义配置的定义:

为asp.net程序添加自定义配置区域using System;
为asp.net程序添加自定义配置区域
为asp.net程序添加自定义配置区域
namespace myconfig
}

接下来关键的一步就是创建用于处理刚才定义好了的MySettings这类配置的MyConfigHandler,需要实现IConfigurationSectionHandler接口,IConfigurationSectionHandler只有一个方法:

object Create(
  
object parent,
   object configContext,
   XmlNode section
 );

因为web.config文件是一个标准的xml文件,所以可以非常简单得读出其中XmlNode的值:

为asp.net程序添加自定义配置区域using System;
为asp.net程序添加自定义配置区域
using System.Configuration;
为asp.net程序添加自定义配置区域
using System.Xml;
为asp.net程序添加自定义配置区域
为asp.net程序添加自定义配置区域
namespace myconfig
}

至此所有的自定义配置类和Handler都已经创建好了,最后只要告诉web.config用MyConfigHandler来处理MySettings就可以了,需要在web.config添加下列内容:

为asp.net程序添加自定义配置区域    <configSections>
为asp.net程序添加自定义配置区域        
<section name="MySettings" type="myconfig.MyConfigHandler,myconfig"></section>
为asp.net程序添加自定义配置区域    
</configSections>
为asp.net程序添加自定义配置区域    
为asp.net程序添加自定义配置区域    
<MySettings>
为asp.net程序添加自定义配置区域        
<SomeSetting>This is a customer configuration setting.</SomeSetting>
为asp.net程序添加自定义配置区域    
</MySettings>

其中<configSecions>告诉web.config调用MyConfigHandler来处理MySettings,<MySettings>中保存的就是自定义的配置内容,例如在某个web page中执行如下代码:

为asp.net程序添加自定义配置区域        private void Page_Load(object sender, System.EventArgs e)
msdn中相关的文章。

相关文章:

  • 2022-12-23
  • 2022-01-04
  • 2021-07-11
  • 2022-02-10
  • 2022-01-25
  • 2022-12-23
  • 2022-12-23
  • 2021-09-24
猜你喜欢
  • 2022-12-23
  • 2022-01-05
  • 2021-08-15
  • 2022-12-23
相关资源
相似解决方案