我們通常把諸如sql的connection string之類的配置資訊儲存在web.config的AppSettings部分,以方便程式的分發,並且可以通過以下方法在程式中獲得:
string sqlStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
對於結構比較複雜的自訂配置,可以通過實現IConfigurationSectionHandler介面來實現這種機制。首先,建立MySettings類,該類僅包含了我需要的一些自訂配置的定義:
using System;
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;
}
}
}
至此所有的自訂配置類和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>
其中<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);
}
得到的結果將會是在用戶端顯示This is a customer configuration setting。其實還有另一種更簡單的方法,就是利用NameValueFileSectionHandler,但是在添加配置資訊時需要像在AppSettings中那樣用<add name="" value=""></add>來添加索引值,對於自訂配置來說意義不大,具體可以參考msdn中相關的文章。
Justin同學總是push我要多發些技術貼,否則就有點對不起他推薦我到這裡來了,過兩天有空的話就再寫些關於自訂httpHandlers和httpModules的文章吧,hoho,被人push真不爽。