自訂配置節處理實現個人化web.config
來源:互聯網
上載者:User
通過System.Configuration中的ConfigurationSettings類的AppSettings屬性,可以很方便訪問web.config設定檔中appSettings節點的資料。對於web程式利用這個設定檔存放一些唯讀程式資訊,比如程式名稱,作者資訊,資料庫連接字串等將是十分方便有用。如:
<!--Sample.aspx-->
private void Page_Load(object sender, System.EventArgs e)
{
this.tbName = ConfigurationSettings.AppSettings[“AppName“];
}
<!--web.config-->
<configuration>
<appSettings>
<add key="AppName" value="MyApplication" />
</appSettings>
... ...
對於ConfigurationSettings類有個方法GetConfig(string sectionName)可以訪問任何配置元素,對於以上例子,可如此使用:
<!--Sample.aspx-->
private void Page_Load(object sender, System.EventArgs e)
{
object settings = ConfigurationSettings.GetConfig(“appSettings“);
NameValueCollection nvc = settings as NameValueCollection;
if (nvc != null)
{
string val = (string)nvc[“AppName“];
this.tbName = val;
}
}
可見GetConfig()方法返回了一個配置處理的對象,轉換成NameValueCollection的執行個體後,可以訪問到該section內的內容了。其實對於設定檔檢索有背後的處理常式實現,同時我們可以看到在web.config,或machine.config中看到對於處理常式的聲明,如:
<!--web.config-->
<configuration>
<configSections>
<section name="mySection"
type="Chagel.Configration.Settings, Configuration" />
</configSections>
<mySection>
<AppName> MyApplication</AppName>
</mySection>
... ...
以上聲明了一個mySection元素,並在configSections中聲明了該配置的處理常式類名為Chagel.Configration.Settings,Configuration為程式集名稱。接下來我們可以通過一個實現System.Configuration.IConfigurationSectionHandler介面的類來處理該配置元素,如: