|
<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) |
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 |
進程反彈之前.所允許的在隊列中等待的請求數量 |
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數 |
userName |
SYSTEM | MACHINE | username |
MACHINE |
運行工作者進程所需的Windows身份 |
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的最多工作者線程量 |
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類,實現自定義配置。