天天看點

在web.config裡自定義配置節

在web.config裡自定義配置節

  版本: 1.0

日期:2005-02-01

作者:[email protected]

說明:在web.config裡自定義配置節,使用自定義的配置解析類

自定義配置節

配置檔案是.NET Framework 定義的一組實作配置設定的标準的XML檔案。web.config則是ASP.NET 程式的配置檔案。

我們很容易就可以在web.config裡增加自定義配置節。

1.在web.config裡增加新的節點

msdn裡的例子寫的很清楚,要先寫配置節的定義configSections。這個必須是<configuration>的第一個元素。

另外,type屬性是配置解析類的類名(包括命名空間)和程式集名稱。

這裡用的是sysytem裡已定義的NameValueSectionHandler。

<configuration>

    <configSections>

        <sectionGroup name="myGroup">

            <sectionGroup name="nestedGroup">

                <section name="mySection" type="System.Configuration.NameValueSectionHandler,System"/>

            </sectionGroup>

        </sectionGroup>

    </configSections>

<myGroup>

    <nestedGroup>

        <mySection>

            <add key="key_one" value="1"/>

            <add key="key_two" value="2"/>

        </mySection>

    </nestedGroup>

</myGroup>

</configuration>

2.增加自定義的配置解析類

雖然framework已定義了幾個配置解析類,但有時候我們要插入我們特定的解析方式,很簡單,隻要寫一個類,實作IConfigurationSectionHandler接口即可。這個接口隻有一個成員,讀入的是相應的配置節,傳回值即是我們用GetConfig得到的内容,也就是說,我們想通過這些配置,得到什麼傳回結果,在這裡寫就可以了。

Create 由所有配置節處理程式實作,以分析配置節的 XML。傳回的對象被添加到配置集合中,并通過 GetConfig 通路。

下面是一個簡單的例子:

public class SpecialSectionHandler : IConfigurationSectionHandler
    {
        public virtual object Create(object parent, object context, XmlNode section)
        {
            Hashtable htResult = new Hashtable();
            for(int i=0;i<section.ChildNodes.Count;i++)
            {
                XmlNode node = section.ChildNodes[i];
                htResult[node.Attributes[KeyAttributeName].Value] = "I am a good guy ,and the value is "+Convert.ToString(node.Attributes[ValueAttributeName].Value);
            }
            return htResult;
        }

        public string KeyAttributeName
        {
            get
            {
                return "key";
            }
        }

        public string ValueAttributeName
        {
            get
            {
                return "value";
            }
        }      

如何使用自定義的解析類呢?在type裡填上這個類的相關資訊即可。類型名和程式集名。

<section name="mySection" type="WebApplication1.SpecialSectionHandler,WebApplication1"/>