.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應用中 訪問自己定義的節點了。