自訂配置節處理實現個人化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介面的類來處理該配置元素,如:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.