string sqlStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
对于结构比较复杂的自定义配置,可以通过实现IConfigurationSectionHandler接口来实现这种机制。首先,创建MySettings类,该类仅包含了我需要的一些自定义配置的定义:
using System;
namespace myconfig
{
public class MySettings
{
public string SomeSetting; //自定义一个string类型的配置信息
public MySettings()
{
}
}
}
namespace myconfig
{
public class MySettings
{
public string SomeSetting; //自定义一个string类型的配置信息
public MySettings()
{
}
}
}
接下来关键的一步就是创建用于处理刚才定义好了的MySettings这类配置的MyConfigHandler,需要实现IConfigurationSectionHandler接口,IConfigurationSectionHandler只有一个方法:
object Create(
object parent,
object configContext,
XmlNode section
);
因为web.config文件是一个标准的xml文件,所以可以非常简单得读出其中XmlNode的值:
using System;
using System.Configuration;
using System.Xml;
namespace myconfig
{
public class MyConfigHandler: IConfigurationSectionHandler
{
public MyConfigHandler()
{
}
public object Create(object parent, object input, XmlNode node)
{
MySettings myset = new MySettings();
foreach (XmlNode n in node.ChildNodes)
{
switch (n.Name)
{
case("SomeSetting"): //从web.config读取SomeSetting的值
myset.SomeSetting = n.InnerText;
break;
default:
break;
}
}
return myset;
}
}
}
using System.Configuration;
using System.Xml;
namespace myconfig
{
public class MyConfigHandler: IConfigurationSectionHandler
{
public MyConfigHandler()
{
}
public object Create(object parent, object input, XmlNode node)
{
MySettings myset = new MySettings();
foreach (XmlNode n in node.ChildNodes)
{
switch (n.Name)
{
case("SomeSetting"): //从web.config读取SomeSetting的值
myset.SomeSetting = n.InnerText;
break;
default:
break;
}
}
return myset;
}
}
}
至此所有的自定义配置类和Handler都已经创建好了,最后只要告诉web.config用MyConfigHandler来处理MySettings就可以了,需要在web.config添加下列内容:
<configSections>
<section name="MySettings" type="myconfig.MyConfigHandler,myconfig"></section>
</configSections>
<MySettings>
<SomeSetting>This is a customer configuration setting.</SomeSetting>
</MySettings>
<section name="MySettings" type="myconfig.MyConfigHandler,myconfig"></section>
</configSections>
<MySettings>
<SomeSetting>This is a customer configuration setting.</SomeSetting>
</MySettings>
其中<configSecions>告诉web.config调用MyConfigHandler来处理MySettings,<MySettings>中保存的就是自定义的配置内容,例如在某个web page中执行如下代码:
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
MySettings myset;
myset = System.Configuration.ConfigurationSettings.GetConfig("MySettings") as MySettings;
Response.Write(myset.SomeSetting);
}
{
// Put user code to initialize the page here
MySettings myset;
myset = System.Configuration.ConfigurationSettings.GetConfig("MySettings") as MySettings;
Response.Write(myset.SomeSetting);
}
得到的结果将会是在客户端显示This is a customer configuration setting。其实还有另一种更简单的方法,就是利用NameValueFileSectionHandler,但是在添加配置信息时需要像在AppSettings中那样用<add name="" value=""></add>来添加键值,对于自定义配置来说意义不大,具体可以参考msdn中相关的文章。
Justin同学总是push我要多发些技术贴,否则就有点对不起他推荐我到这里来了,过两天有空的话就再写些关于自定义httpHandlers和httpModules的文章吧,hoho,被人push真不爽。