web.config配置詳細說明


(一).Web.Config是以XML文件規范存儲,配置文件分為以下格式

    1.配置節處理程序聲明
    特點:位於配置文件的頂部,包含在<configSections>標志中。

    2.特定應用程序配置
    特點: 位於<appSetting>中。可以定義應用程序的全局常量設置等信息.

    3.配置節設置
    特點: 位於<system.Web>節中,控制Asp.net運行時的行為.

    4.配置節組
    特點: 用<sectionGroup>標記,可以自定義分組,可以放到<configSections>內部或其它<sectionGroup>標記的內部.

    (二).配置節的每一節
    1.<configuration>節
    根元素,其它節都是在它的內部.
    
     2.<appSetting>節
    此節用於定義應用程序設置項。對一些不確定設置,還可以讓用戶根據自己實際情況自己設置
    用法:
     I.
        <appSettings>
           <add key="Conntction" value="server=192.168.85.66;userid=sa;password=;database=Info;"/>
        <appSettings>
        定義了一個連接字符串常量,並且在實際應用時可以修改連接字符串,不用修改程式代碼.
    II.
        <appSettings>
          <add key="ErrPage" value="Error.aspx"/>
        <appSettings>
        定義了一個錯誤重定向頁面.
    III.

       <appSettings configSource="source/new.xml"/>可以通過新的XML來擴展配置內容。

      new.xml寫法為:

       <?xml version="1.0" encoding="utf-8" ?>

        <appSettings>

          <add key="" value="|"/>

        </appSettings>

    3.<compilation>節
    格式:
        <compilation defaultLanguage="c#" debug="true" />
     I.
        default language: 定義后台代碼語言,可以選擇C#和VB.net兩種語言.
     II.
        debug : 為true時,啟動aspx調試;為false不啟動aspx調試,因而可以提高應用程序運行時的性能。一般程序員在開發時設置為true,交給客戶時設置為false.

    4.<customErrors>節
    格式:
        <customErrors mode="RemoteOnly" defaultRedirect="error.aspx"
            <error statusCode="440" redirect="err440page.aspx"/>
            <error statusCode="500" redirect="err500Page.aspx"/>
        />
    I.
        mode : 具有On,Off,RemoteOnly 3種狀態。On表示始終顯示自定義的信息; Off表示始終顯示詳細的asp.net錯誤信息; RemoteOnly表示只對不在本地Web服務器上運行的用戶顯示自定義信息.
    II.
        defaultRedirect: 用於出現錯誤時重定向的URL地址. 是可選的
    III.
        statusCode: 指明錯誤狀態碼,表明一種特定的出錯狀態.
    IV.
        redirect:錯誤重定向的URL.

    5.<globalization>節
    格式:
        <globalization requestEncoding="utf-8" responseEncoding="utf-8" fileEncoding="utf-8" />
    I.
        requestEncoding: 它用來檢查每一個發來請求的編碼.
    II.
        responseEncoding: 用於檢查發回的響應內容編碼.
    III.
        fileEncoding: 用於檢查aspx,asax等文件解析的默認編碼.

    6.<sessionState>節
    格式:
        <sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20" />
    I.
        mode: 分為off,Inproc,StateServer,SqlServer幾種狀態
    II.
        stateConnectionString :指定Asp.net應用程序存儲遠程會話狀態的服務器名,默認為本機
    III.
        sqlConnectionString: 當用會話狀態數據庫時,在這里設置連接字符串
    IV.
        Cookieless: 設置為true時,表示不使用cookie會話狀態來標識客戶; 否則,相反.
    V.
        TimeOut: 用來定義會話狀態存儲的時間,超過期限,將自動終止會話.

    7.<authentication>節
    格式:
        <authentication mode="Forms">
          <forms name=".ASPXUSERDEMO" loginUrl="Login.aspx" protection="All" timeout="30"/>
          </authentication>
          <authorization>
          <deny users="?"/>
        </authorization>
    I.
        Windows: 使用IIS驗證方式
    II.
        Forms: 使用基於窗體的驗證方式
    III.
     Passport: 采用Passport cookie驗證模式
    IV.
        None: 不采用任何驗證方式

     里面內嵌Forms節點的屬性涵義:
    I.
        Name: 指定完成身份驗證的Http cookie的名稱.
    II.
        LoginUrl: 如果未通過驗證或超時后重定向的頁面URL,一般為登錄頁面,讓用戶重新登錄
    III.
        Protection: 指定 cookie數據的保護方式.

        可設置為: All None Encryption Validation四種保護方式
            a. All表示加密數據,並進行有效性驗證兩種方式
            b. None表示不保護Cookie.
            c. Encryption表示對Cookie內容進行加密
            d. validation表示對Cookie內容進行有效性驗證
    IV.
        TimeOut: 指定Cookie的失效時間. 超時后要重新登錄.

 

    從文件名就可以看出是做配置用的,比如配置自定義錯誤頁面,debug,等等
    存放連接字符串是最基本的用法,
    高級一點可以配置httpmodule,httphandler...
    再高級一點可以寫一個繼承自IConfigurationSectionHandler,添加自定義的配置節...
    功能是很強大的
    ASP.NET提供了一個豐富而可行的配置系統,以幫助管理人員輕松快速的建立自己的WEB應用環境。    ASP.NET提供的是一個層次配置架構,可以幫助WEB應用、站點、機器分別配置自己的擴展配置數據。    ASP.NET的配置系統具有以下優點:
    ●ASP.NET允許配置內容可以和靜態內容、動態頁面和商業對象放置在同一應用的目錄結構下。當管理人員需要安裝新的ASP.NET應用時,只需要將應用目錄拷貝到新的機器上即可。
    ●ASP.NET的配置內容以純文本方式保存,可以以任意標准的文本編輯器、XML解析器和腳本語言解釋、修改配置內容。
    ●ASP.NET 提供了擴展配置內容的架構,以支持第三方開發者配置自己的內容。
    ●ASP.NET配置文件的更修被系統自動監控,無須管理人員手工干預。


     4.2.2配置文件的規則
    ASP.NET的配置文件是基於XML格式的純文本文件,存在於應用的各個目錄下,統一命名為“config.web”。它決定了所在目錄及其子目錄的配置信息,並且子目錄下的配置信息覆蓋其父目錄的配置。

    WINNT\Microsoft.NET\Framework\版本號\下的config.web為整個機器的根配置文件,它定義了整個環境下的缺省配置。

    缺省情況下,瀏覽器是不能夠直接訪問目錄下的config.web文件。

    在運行狀態下,ASP.NET會根據遠程URL請求,把訪問路徑下的各個config.web配置文件疊加,產生一個唯一的配置集合。舉例來說,一個對URL: http://localhost/webapp/owndir/test.aspx的訪問,ASP.NET會根據以下順序來決定最終的配置情況:
    1..\Microsoft.NET\Framework\v.1.00\config.web (缺省配置文件)
    2..\webapp\config.web (應用的配置)
    3..\webapp\owndir\config.web (自己的配置)


    4.2.3配置文件的語法規則

   (1)標識
    配置內容被置於config.web文件中的標記<configuration>和</configuration>之間。
    格式:
        <configuration>
            配置內容…
        </configuration>

    (2)配置段句柄說明
    ASP.NET的配置文件架構並未指定任何文件格式或者是支持的配置屬性。相反的,它提出了“配置段句柄申明”的概念來支持任意的用戶定義配置段。
    格式:
        <configsections>
          <add name=欲定義配置段名 type=處理的句柄函數 />
        </configsections>

    (3)配置段
    具體定義配置的內容,供應用使用。

    以下例子定義了一個“httpmodules”配置段,設置了系統http相關的處理模塊
<configuration>
     <configsections>
       <add name="httpmodules" type="System.Web.Configuration.HttpModules ConfigurationHandler" />
     </configsections>

    <httpmodules>
       <add type="System.Web.SessionState.CookielessSessionModule" />
      <add type="System.Web.Caching.OutputCacheModule" />
      <add type="System.Web.SessionState.SessionStateModule" />
       <add type="System.Web.Security.WindowsAuthenticationModule" />
      <add type="System.Web.Security.CookieAuthenticationModule" />
      <add type="System.Web.Security.PassportAuthenticationModule" />
      <add type="System.Web.Security.CustomAuthenticationModule" />
      <add type="System.Web.Security.UrlAuthorizationModule" />
       <add type="System.Web.Security.FileAuthorizationModule" />
    </httpmodules>
</configuration>


    4.2. 4   ASP.NET定義的標准配置段

(1)httpmodule    段: 定義了應用的http請求的處理模塊以及諸如安全、日志之類的應用方式
(2)httphandlers 段: 負責映射URLs到IhttpHandler類
(3)sessionstat    段: 負責配置http模塊的會話狀態
(4)globalization   段:配置應用的公用設置
(5)compilation    段: 配置ASP.NET的編譯環境
(6)trace      段:配置ASP.NET的跟蹤服務
(7)security         段: ASP.NET的安全配置
(8)iisprocessmodel 段: 在IIS上配置ASP.NET的處理模式
(9)browercaps   段: 配置瀏覽器的兼容部件


    4.2. 5    一個配置讀出的例子

(1)config.web配置文件

    <!--config.web 請放入FormCfg.aspx所在目錄-->
      <configuration>
          <!--申明一個test配置段-->
          <configsections>
              <add name="test" type="System.Web.Configuration.DictionarySectionHandler" />
          </configsections>

          <test>
              <!--配置一個鍵key,其內容為just a configure test-->
              <add key="key" value="just a configure test" />
          </test>
      </configuration>

(2)讀出其內容

    <!--文件名:Application/FormCfg.aspx-->
    <html>
    <head>
    <script language="VB" runat=server>
        sub page_load(s as object ,e as eventargs)
        '取出test配置段的key鍵的值
        Dim CfgSection As Hashtable = Context.GetConfig("test")
         Dim Msg As String = CStr(CfgSection("key"))

        lblMsg.text=Msg
        end sub
    </script>
    <title>配置信息的讀取</title>
    </head>
    <body>
        <center>
            config.web中"test"配置段中key的內容為: <asp:label id=lblmsg runat=server />
        </center>
     </body>
    </html>

(3)運行結果


    4.2. 6    Config.web配置實例
    <configuration>
        <!--定義用戶應用的公用設置,如SQL的sql連接串等等-->
        <appsettings></appsettings>

        <!--設置瀏覽器的兼容性部件-->
        <browsercaps></browsercaps>

        <!--編譯環境設置,非調試模式-->
        <compilation debugmode="false">

            <!--缺省編譯語言為vb,以后可以不再在Page中定義腳本語言-->
            <compilers defaultlanguage="vb">

            <!--以MSVSA.dll編譯.vb為后綴的VB文件-->
            <compiler language="VB" extension=".vb" type="MSVSA.dll#Microsoft.VB.Compiler"/></compilers>

            <assemblies>
                <!--加入對System.Data的引用-->
                <add assembly="System.Data" />

                <!--去掉對System.Data的引用-->
                <remove assembly="System.IO" />

                <!--去掉config.web中包含或繼承來的引用-->
                <clear />
            </assemblies>
        </compilation>

        <!--設置應用全局環境-->
            <!--文件、請求、返回以gb2312編碼,以保證瀏覽器正確顯示中文-->
            <globalization fileencoding="gb2312" requestencoding="gb2312" responseencoding="gb2312"/>

            <!--定義用戶出錯的處理-->
            <!--出錯缺省顯示defaultredirect指定的頁面,mode為on時,遵循customerrors配置段-->
            <!--mode為off時,忽略用戶出錯,mode為remoteonly時,本地才顯示真正的出錯原因-->
            <customerrors defaultredirect="AnErrorHasOccured.aspx?ErrNum=-1" mode="remote">

                <!--當出錯碼為500時,顯示redirect指定的頁面-->
                <error statuscode="500" redirect="AnErrorHasOccured.aspx?ErrNum=500"/>
            </customerrors>

            <!--指定目錄webapp的訪問權限-->
            <location path="webapp” >
                <!--非授權用戶不能進入webapp目錄-->
                <security>
                <authorization>
                <deny users="?" />
                </authorization>
                </security>
             </location>

            <!--定義安全屬性-->
             <security>
                <authorization>

                <!--角色為Adminstrators和所有的用戶訪問其指定的資源-->
                <allow roles="Adminstrators"/>
                <allow users="*" />
                 </authorization>
             </security>
    </configuration>

 <configuration>//頂層元素
<system.web>//大多應用程序設置位於此元素下
<sessionState mode='Inproc' timeout='10' />//設置會話狀態超時時間
</system.web>
</configuration>

Table 3-1.可用於web.config的頂層配置元素

元素Element

含義Purpose

<authentication>

指定所使用的客戶身份驗證模式Specify the client authentication mode to use

<authorization>

允許或者拒絕用戶或角色的訪問Allow or deny users or roles access

<browserCaps>

根據用戶代理指定瀏覽器的能力Specify browser capabilities based on user agent

<clientTarget>

定義客戶目標Define client targets

<compilation>

控制同頁編譯和程序集引用Control page compilation and assembly references

<customErrors>

控制錯誤頁顯示和定義自定義的錯誤頁Control error page display and define custom error pages

<globalization>

設置請求和響應的編碼Set the request and response encoding

<httpHandlers>

添加或移除HTTP處理程序Add or remove HTTP handlers

<httpModules>

添加或移除HTTP模塊Add or remove HTTP modules

<httpRuntime>

控制HTTP請求的處理Control aspects of HTTP request processing

<identity>

為該應用程序指定標識Specify impersonation for this application

<machineKey>

控制驗證和解密的鑰匙Control the validation and decryption key

<pages>

設置全局的網頁默認屬性Set defaults for page attributes globally

<processModel>

控制工作者進程的行為方式Control the behavior of the worker process

<securityPolicy>

使用相關的策略文件定義信任等級Define trust levels with associated policy files

<sessionState>

控制會話狀態Control session state

<trace>

啟用應用程序范圍的跟蹤Enable application-wide tracing

<trust>

選擇使用的信任等級Select which trust level to use

<webServices>

指定Web服務的協議和范圍Specify Web service protocols and extensions

<appSettings>

添加應用程序專用的數據元素Add application-specific data elements


1, 配置的四個層次

(1)機器:machine.config:位於$FRAMEWORK\CONFIG($FRAMEWORK一般是c:\winnt\Microsoft.NET\Framework\v1.0.3705),
是.net必須備的默認配置文件。
web.config用來修改.net默認配置。
(2)站點:web站點根目錄下的web.config,影響全站配置
(3)程序:應用程序虛目錄根下的web.config,影響全虛目錄配置
(3)子目錄:虛目錄的子目錄下的web.config,影響該子目錄及其子目錄下配置

Figure 3-1. Hierarchy of Configuration Files

[圖片]

2,通過location元素簡化web.config配置:

Listing 3-2 Using the location Element

<configuration>
<location path="bar">//作用就相當於在bar目錄下配置了指定的web.config配置
<system.web>
<httpHandlers>
<remove verb="*" path="*.ashx" />
</httpHandlers>
</system.web>
</location>
</configuration>


3,元素的配置規定:
authentication, sessionState, trust, 和 httpModules(即使在老版本.net允許在子目錄中配置,也是不生效的)元素屬於應用程序級別的元素,不能配置於子目錄下的 web.config。processModel屬於機器級別元素,只能用於machine.config。

4,元素的更改生效時間:
一般web.config更改后,會自動重新加載程序,並放棄原進程的會話狀態和程序狀態。如果是processModel更改,只有終止工作者進程(可手工IIS復位,可撤銷aspnet_wp.exe進程,也可因進程意外反彈自身)然后重新啟動,才能應用新配置,同時放棄所有運行於該機器上的.net 程序狀態,緩存數據和會話狀態。

5,IIS與web.config配置
如果使用了IIS,則IIS的安全配置等優秀於.net配置。如此可以只使用IIS默認配置,而在web.config中具體配置。

二,常量配置appSettings
使用appSettings元素的add子元素的key和value屬性(鍵值不分大小寫)來存儲常量設置。

Listing 3-3 Specifying Application-Specific Configuration Data

<!— File: web.config —>
<configuration>
<appSettings>
<add key="DSN"
value="server=localhost;uid=sa;pwd=;database=pubs"
/>
<add key="bgColor" value="white" />
</appSettings>
</configuration>
程序啟動后,配置就載入內存,有訪問權限(.net使用HttpForbiddenHandler來控制對.config.cs, .vb, .asax, .resx文件的訪問權限,默認下外部程序不可訪問配置文件)的程序就可以使用ConfigurationSettings.AppSettings ["DSN"]的方式直接引用配置的值。

Listing 3-4 Retrieving appSettings Configuration Data

<!— File: samplepage.aspx —>
<%@ Page Language='C#' %>
<%@ Import Namespace='System.Configuration' %>

<script runat=server>
protected void Page_Load(object src, EventArgs e)
{
string dsn = ConfigurationSettings.AppSettings["DSN"];
// use dsn to connect to a database...

string bgColor =
ConfigurationSettings.AppSettings["bgColor"];
// use retrieved background color...
}
</script>

<!— remainder of page not shown —>

三,進程配置processModel
只能在machine.config中使用processModel,其改動只在aspnet_wp.exe進程重啟后生效,並由unmanaged (非托管?)的aspnet_isapi.dll(ISAPI擴展dll)讀取,而非象其他配置一樣由managed mechanism(托管機制?)讀取。

Table 3-2. Attributes of the processModel Element

Attribute

Values

Default

Description

Enable

true | false

true

指定ASP.NET是駐留在外部工作者進程中(true),還是直接在inetinfo.exe中(false)
Whether ASP.NET is hosted in an external worker process (true) or directly in inetinfo.exe (false)

timeout

Infinite | HH:MM:SS

Infinite

進程的總生命期——超時后進程反彈Total life of a process—process bounced after timeout

idleTimeout

Infinite | HH:MM:SS

Infinite

進程的總空閑期——當到達超時時間時進程反彈Total idle life of a process—process bounced when reached

shutdownTimeout

Infinite | HH:MM:SS

0:00:05

在撤消進程之前,給予進程關閉的時間Time given to process to shut down before being killed

requestLimit

Infinite | number

Infinite

進程反彈之前,要服務的總需求量Total number of requests to serve before bouncing process

requestQueueLimit

Infinite | number

5000

進程反彈之前.所允許的在隊列中等待的請求數量
Number of queued requests allowed before bouncing process

restartQueueLimit

Infinite | number

10

進程重啟時.在隊列中等待的請求量Number of requests kept in queue while process is restarting

memoryLimit

Number

60

進程反彈之前.允許進程使用的物理內存百分數Percentage of physical memory process is allowed to use before bouncing process

webGarden

true | false

false

指定進程是否與特定CPU建立密切關系(對於多CPU機器)Whether process should be affinitized with a particular CPU (for multi-CPU machines)

cpuMask

Bitmask

0xffffffff

控制ASP.NET工作者進程所用的CPU數
(webGarden必須為true)Controls number of CPUs available for ASP.NET worker processes (webGarden must be true)

userName

SYSTEM | MACHINE | username

MACHINE

運行工作者進程所需的Windows身份
(MACHINE使用低特權的ASPNET賬號)Windows identity to run the worker process in (MACHINE uses low-privileged ASPNET account)

Password

AutoGenerate | password

AutoGenerate

username的密碼Password for username

logLevel

All | None | Errors

Errors

登記在事件日志中的事件類型Event types logged to event log

clientConnectedCheck

HH:MM:SS

0:00:05

執行客戶連接的檢查前.請求保留在隊列中的時間Time a request is left in the queue before a client-connected check is performed

comAuthenticationLevel

Default | None | Connect | Call | Pkt | PktIntegrity | PktPrivacy

Connect

DCOM的安全性身份驗證的級別Level of authentication for DCOM security

comImpersonationLevel

Default | Anonymous | Identify | Impersonate | Delegate

Impersonate

COM的安全性身份驗證的級別Authentication level for COM security

responseRestartDeadlockInterval

Infinite | HH:MM:SS

00:09:00

由於responseRestart-DeadlockInterval而重啟工作者進程所需的等待時間Time to wait between restarting worker process because of responseRestartDeadlockInterval

responseDeadlockInterval

Infinite | HH:MM:SS

00:03:00

在隊列中有等待的請求時,為監測死鎖而設定的響應超時For deadlock detection, timeout for responses when there are queued requests

maxWorkerThreads

Number

25

線程池中每個CPU的最多工作者線程量
Maximum number of I/O threads per CPU in the thread pool

maxIoThreads

Number

25

線程池中每個CPU的最多I./O線程量Maximum number of I/O threads per CPU in the thread pool

serverErrorMessageFile

File name

""

“Server Unavailable"消息的自定義Customization for "Server Unavailable" message


  雖然如上有眾多條件能使進程反彈,但默認下只有兩個反彈條件:一是程序占用了60%以上的物理內存(該條件由memoryLimit屬性來指定),二是有5000多個請求在隊列中等待。常用的反彈條件還有明確的超時時間 (timeout),空閑超時時間(累計空閑時間idleTimeout),工作者進程的服務數量上限(requestLimit)。
  可以通過設置webGarden和 cpuMask來設置多cpu的使用方式

Listing 3-5 Specifying Multiple Worker Processes on a Multi-CPU machine

<processModel enable="true"
timeout="Infinite"
idleTimeout="Infinite"
shutdownTimeout="0:00:05"
requestLimit="Infinite"
requestQueueLimit="5000"
restartQueueLimit="10"
memoryLimit="60"
webGarden="true"//啟用該配置后,每個cpu運行一個工作者進程,進程間不能共享會話狀態,數據緩存,程序狀態
cpuMask="0x00000007"//相當於二進制0...0111屏蔽,則只使用cpu0,cpu1,cpu2,屏蔽其他cpu
userName="machine"
password="AutoGenerate"
logLevel="Errors"
clientConnectedCheck="0:00:05"
comAuthenticationLevel="Connect"
comImpersonationLevel="Impersonate"
responseRestartDeadlockInterval="00:09:00"
responseDeadlockInterval="00:03:00"
maxWorkerThreads="25"
maxIoThreads="25" />


  還可以設置maxIoThreads和maxWorkerThreads來控制CPU。(前者一定是I/O(如流或管道)實現端口,后者則是傳統非限制流程。由於目前IIS采用異步寫已命名管道的方法來處理請求(IIS6直接集成了asp.net,所以不必通過已命名管道而是在工作者線程中直接處理請求),所以.net主要也在I/O中處理請求。)默認的線程設置是25/CPU,一般已經夠用。當需要設置超過25直到100線程時,需要謹慎檢查是否有異常。

1, 讀取進程信息
使用ProcessModelInfo(兩個獲得當前或剛終止工作者進程休息的方法,都調用ProcessInfo類)和ProcessInfo(保存工作者進程的信息)兩個靜態類來讀取進程信息

Listing 3-6 ProcessModelInfo and ProcessInfo Classes

public class ProcessModelInfo
{
public static ProcessInfo GetCurrentProcessInfo();
public static ProcessInfo[] GetHistory(int num);
}

public class ProcessInfo
{
public TimeSpan Age {get;}//年齡
public int PeakMemoryUsed {get;}//已使用最大內存數
public int ProcessID {get;}//進程ID
public int RequestCount {get;}//已服務的請求數
public ProcessShutdownReason ShutdownReason {get;}//關閉原因
public DateTime StartTime {get;}//開始時間
public ProcessStatus Status {get;}//狀態
}

Figure 3-3. Sample ProcessModelInfo Output

[圖片]


2 , IIS6.0進程模型的改變(相對IIS5的隔離方式)
  在IIS6.0中,ProcessModel在IIS元數據庫中被對等設置代替,現在以XML形式放在metabase.xml文件中,所以忽略了 machine.config中的ProcessModel元素。而且進程不再是ASPNET_wp.exe,而是一個或多個w3wp.exe中,因為已經不限制一個cpu只能一個工作者進程。我們可以配置應用程序池(包含共享相同工作者進程的虛目錄集),通過比ProcessModel更多更靈活的設置來控制進程(循環次數/天,分離虛擬內存極限,實際內存極限,cpu使用監視,cpu過載的回收,應用程序池禁用的錯誤數量極限,啟動和關閉時間限制)。
  另外,使用http.sys的內核模式來偵聽處理Http請求,而不再是inetinfo.exe。這樣就不在進程中而是在系統服務內核中處理Http要求,於是即使用戶模式進程出現缺陷甚至崩潰,都不會影響服務內核。

四,附屬設置

1,assemblies元素
  在web.config中使用@Assembly,可以全局引用GAC部署的應用程序。

Listing 3-7 Adding an Application-wide Reference to a GAC-Deployed Assembly

<configuration>
<!— ... —>
<system.web>
<compilation>
<assemblies>
<add assembly="Util, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a77a5c561934e089" />
</assemblies>
</compilation>
</system.web>
</configuration>
2,pages元素
  在web.config中使用@page指令,可以統一改變應用程序的page默認設置。

Listing 3-8 Using the pages Element

<configuration>
<!— ... —>
<system.web>
<pages enableViewState='false' />
</system.web>
</configuration>
五,讀取配置信息
  除了通過ConfigurationSettings.AppSettings["xxx"]來訪問保存在AppSettings中的值外,通常用 ConfigurationSettings.GetConfig()方法,請求從緩存中讀取,如未緩存就請求直接從配置文件讀入內存, ConfigurationRecord類使用XmlTextReader類可以直接讀取最低層配置的物理xml文件。

Listing 3-9 Reading Configuration Settings

object settings =
ConfigurationSettings.GetConfig("appSettings");
NameValueCollection nvc = settings as NameValueCollection;
if (nvc != null)
{
string val = (string)nvc["xxx"];
}

除了web.config這樣的配置的元數據,還有配置的處理程序(解析配置使其獲得高擴展性,並在正式讀取配置時建立類,同時傳送對象的實例建立,開始傳送相關配置)。如下圖:machine.config中,compilation元素由 CompilationConfigurationHandler類來解析,該類於configSections元素下指定,同時也屬於 sectionGroup元素(進一步確定分析范圍是 system.web)。另外一個元素appSettings由NameValueFileSectionHandler負責解析,該元素位於配置文件的頂層。

Figure 3-4. Configuration Section Handlers in machine.config

[圖片]

每個configSections中的元素都必須實現IConfigurationSectionHandler接口,該接口有一個簡單的方法 Create。當配置處理程序的標簽被讀入時,ConfigurationRecord類(頂層配置文件解析器)調用Create方法。同時,處理程序獲得上層配置信息(如果有上層配置的話)和當前HttpConfigurationContext對象(通過輸入參數),以及對 XmlNode的引用(最重要信息,由配置處理程序負責解析)。通常處理程序(函數)會遍歷XmlNode的每個子節點和屬性,返回一個對象,包含所有狀態信息。在緩存上述狀態信息后,應用程序就可通過ConfigurationSettings.GetConfig()全局引用該狀態信息。

Listing 3-10 IConfigurationSectionHandler Interface

public interface IConfigurationSectionHandler
{
object Create(object parent, object input, XmlNode node);
}
asp.net配置部份的處理程序各自都會在內存中建立一個state retainer(狀態保持器),如CompilerConfiguration類(compilation元素信息), PagesConfiguration類(pages元素信息 )等。這些配置實例類(都是內部類,不可直接訪問,asp.net用它們來設置其創建類中的默認值和其它值)都保存在一個全局的哈希表中,可以用 ConfigurationSettings.GetConfig()來訪問該哈希表。

Figure 3-5. In-memory Configuration Settings Layout

[圖片]



六,創建自定義的配置處理程序
除了保存在appSettings元素中之外,還可以自定義配置元素。如下:

Listing 3-11 Sample Custom Configuration Element

<!— File: web.config —>
<configuration>
<acmeGroup>
<acme>//指定自定義元素
<font>Courier New</font>
<backgroundColor>Green</backgroundColor>
<underlineLinks>true</underlineLinks>
<horizontalWidth>600</horizontalWidth>
<verticalWidth>800</verticalWidth>
</acme>
</acmeGroup>
</configuration>
首先,我們要建立用於保存配置狀態信息的保存機制。
一種較簡單的方法是定義一個類(如AcmeSettings類),用其中的公有數據成員來保存對應的配置元素。

Listing 3-12 Sample Custom Configuration Settings State Class

// File: AcmeSettings.cs
namespace EssentialAspDotNet.Config
{
public class AcmeSettings
{
public string Font;
public string BackgroundColor;
public bool UnderlineLinks;
public int HorizontalWidth;
public int VerticalWidth;
}
}
然后,我們要建立一個實現IConfigurationSectionHandler接口的類,用於解析配置文件中自定義部份,並將其狀態信息保存到acmeSettings類中。

Listing 3-13 Sample Custom Configuration Section Handler

// File: AcmeConfigHandler.cs
namespace EssentialAspDotNet.Config
{
public class AcmeConfigHandler :
IConfigurationSectionHandler
{
public object Create(object parent, object input,
XmlNode node)
{
AcmeSettings aset = new AcmeSettings();

foreach (XmlNode n in node.ChildNodes)
{
switch (n.Name)
{
case ("font"):
aset.Font = n.InnerText;
break;
case ("backgroundColor"):
aset.BackgroundColor = n.InnerText;
break;
case ("underlineLinks"):
aset.UnderlineLinks = bool.Parse(n.InnerText);
break;
case ("horizontalWidth"):
aset.HorizontalWidth = int.Parse(n.InnerText);
break;
case ("verticalWidth"):
aset.VerticalWidth = int.Parse(n.InnerText);
break;
}
}
return aset;
}
}
}
最后要通知,我們要用該類解析配置文件中的acme元素。為此,我們在配置文件的configSections中添加一個section元素,用於讀取並解析配置文件。(系統范圍的machine.config文件,站點范圍和應用程序范圍的web.config文件都能添加Section元素)

Listing 3-14 Installing a Custom Configuration Section Handler

<!— File: web.config —>
<configuration>
<configSections>
<sectionGroup name="acmeGroup">
<section name="acme"
type="EssentialAspDotNet.Config.AcmeConfigHandler, AcmeConfigHandler"
/>
</sectionGroup>
</configSections>
<!— ... —>
</configuration>
現在,應用程序中的所有網頁或者代碼塊,都能使用ConfigurationSettings.GetConfig()方法訪問該配置信息,傳遞我們創建的部份組(section group)和部份名稱(section name),並將結果轉變為我們創建的AcmeSettings類。如下:

Listing 3-15 Accessing Custom Configuration Information

// File: TestAcmeSettings.aspx
protected void Page_Load(object src, EventArgs e)
{
AcmeSettings set;
set = ConfigurationSettings.GetConfig("acmeGroup/acme")
as AcmeSettings;

// use set here (like set.Font, set.BackgroundColor,
// etc.)
}
還有一種方法,使用NameValueFileSectionHandler,就不需要自即編寫實現 IConfigurationSectionHandler接口的類了,而是重用與appSettings元素一樣的類。當然也不能用add元素(帶有鍵 /值對)添加新的配置元素,但也能容易地添加新的配置部份。

Listing 3-16 Adding a Custom Configuration Section with a Prebuilt Handler

<!— File: web.config —>
<configuration>
<configSections>
<section name="myGroup"
type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089"/>//添加了名為myGroup的新的配置的部份
///其type屬性引用了NameValueFileSectionHandler類,該類的實例將其鍵/值對保存在NameValueCollection中供訪問。

</configSections>

<myGroup>
<add key="font" value="Courier New"/>
<add key="backgroundColor" value="Green"/>
<add key="underlineLinks" value="true"/>
<add key="horizontalWidth" value="600"/>
<add key="verticalWidth" value="800"/>
</myGroup>
<!— ... —>
</configuration>

Listing 3-17 Accessing Custom Configuration Information with NameValueCollection

// File: TestAcmeSettings.aspx
protected void Page_Load(object src, EventArgs e)
{
NameValueCollection set;
set = ConfigurationSettings.GetConfig("myGroup")
as NameValueCollection;

// use set here (like set["Font"],
// set["BackgroundColor"], etc.)
}
七,小結:
ASP.NET使用web.config名字的XML文件取代IIS的元數據庫進行配置,machine.config是最頂層的機器配置,而web.config可以放在站點根目錄,虛目錄根部,子目錄等不同層次位置,相應地對其下層發生效用。
另外還可用新的配置元素,appSettings用於保存數據的通用的名/值對,以供應用程序調用。processModel可以精確控制工作者進程。另外還可通過寫一個實現IConfigurationSectionHandler接口的類或者使用系統提供的 NameValueFileSectionHandler類,實現自定義配置。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM