.net 如何在web.config中讀取自訂節點以及注意的問題

來源:互聯網
上載者:User
web|問題 這幾天在做一個urlMapping類庫的時候用到了如何讀取web.config中自訂節點, 做完後覺得挺好 現就製作過程敘述一下。
web.config檔案在web application中起著非常重要的作用。 它本身包含了授權,handler,compilation,globalization,錯誤與跟蹤等一系列設定。但是當你需要一些特殊的或者想添加自己的settings時,應該如何做呢?

要建立自訂設定 要求有2步:寫cs代碼 和 修改web.config

代碼
這裡我們建立了一個簡單的handler , 此handler 用在web.config檔案中。


using System; using System.Collections; using System.Xml; using System.Configuration; using System.Web.Configuration; namespace Devhood { internal class PageStyleHandler:IConfigurationSectionHandler { public virtual object Create(Object parent, Object context, XmlNode node) { PageStyle config = new PageStyle((PageStyle)parent); config.LoadValuesFromConfigurationXml(node); return config; } } public class PageStyle { string _backColour; internal PageStyle(PageStyle parent) { if (parent != null) _backColour = parent._backColour; } internal void LoadValuesFromConfigurationXml(XmlNode node) { XmlAttributeCollection attribCol = node.Attributes; _backColour = attribCol["backColour"].Value; } public string BackColour { get { return _backColour; } } } }



這裡有兩個類:繼承IConfigurationSectionHandler介面的PageStyleHandler類 和 用於從webconfig返回資料的PageStyle類。PageStyle 類可以讀取一個XML 節點(自web.config)並且把節點資料儲存的BackColour屬性中。

設定Web.config檔案
為了能夠訪問PageStyleHandler必須對web.config做相應的配置。


<configuration> <configSections> <sectionGroup name="devhood"> <section name="pageStyle" type="Devhood.PageStyleHandler, PageStyle" /> sectionGroup> configSections> <devhood> <pageStyle backColour="navy" /> devhood> configuration>


這樣就可以在你的web應用中 訪問自己定義的節點了。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.