- A Word on the Metabase
- Walk-Through of web.config's Hierarchical Structure
- System.Configuration and System.Web.Configuration Namespaces
- Accessing web.config Using System.Xml
- Chapter Summary
Walk-Through of web.config's Hierarchical Structure
The web.config file's schema contains the sections defined in Table 7.1.
Table 7.1 Overview of the web.config Sections
Configuration |
Description Section Element |
configuration |
Provides custom configuration. This is where custom appSetting keys are defined. |
mscorlib |
Specifies mapping of configuration algorithm monikers to implementation classes. |
remoting |
Provides customization for remoting. |
runtime |
Specifies how garbage collection is handled and the version assembly for configuration files. |
startup |
Defines what version of the run-time is required to run the application. |
system.diagnostics |
Configures tracing and debugging options and handlers. |
system.net |
Defines how the .NET Framework connects to the Internet. |
system.web |
Customizes ASP.NET application behavior. |
A sample web.config section is shown in Listing 7.1.
Listing 7.1 A sample web.config File
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="connectionString" value="User ID=sa;Password=;Initial Catalog=Northwind;Data Source=AT1LT-3165-03"/> <add key="startupTable" value="Customers"/> </appSettings> <system.web> <processModel enable="true" idleTimeout="00:30:00" pingFrequency="00:01:00" pingTimeout="00:00:30" logLevel="Errors" webGarden="true"/> <compilation defaultLanguage="vb" debug="true" explicit="true" strict="true"/> <customErrors mode="RemoteOnly" > <error statusCode="404" redirect="FileNotFound.aspx" /> <error statusCode="500" redirect="Oops.aspx" /> </customErrors> <authentication mode="Forms" > <forms name="OrderForm" loginUrl="/login.aspx"> <credentials passwordFormat="Clear"> <user name="deanna" password="wife"/> <user name="lilbit" password="son"/> <user name="teenybit" password="unborn"/> </credentials> </forms> </authentication> <authorization> <allow users="Admin" /> <deny users="?" /> </authorization> <trace enabled="true" requestLimit="10" pageOutput="true" traceMode="SortByTime" localOnly="true" /> <sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user
id=sa;password=" cookieless="false" timeout="20" /> <globalization requestEncoding="utf-8" responseEncoding="utf-8" /> </system.web> </configuration>
The web.config file in Listing 7.1 demonstrates the use of two configuration sections: appSettings and system.web. This chapter looks at these sections in detail.
Configuration Files Are Extensive
Many more elements in other sections are out of the scope of this book. For more information on the sections in the configuration file, see the .NET General Framework Reference in the .NET SDK documentation.
The appSettings Configuration Section
The appSettings configuration section defines custom application settings. This section is useful for static configuration information, such as database connection strings. This information can then be easily accessed by using the classes in the System.Configurations namespace (discussed in the section, "System.Configuration and System.Web.Configuration Namespaces").
The system.web Configuration Section
The system.web configuration section allows customization of nearly any aspect of the current application's environment at run-time. ASP.NET builds a collection of settings by using the hierarchy rules illustrated in Figure 7.2 and caches them for subsequent requests for the URL.
Figure 7.2 shows a logical grouping of the sections in the system.web section.
Figure 7.2 A logical grouping of the system.web subsections.
The following subsections in the system.web section are the focus of this chapter:
<authentication>
<authorization>
<browserCaps>
<compilation>
<customErrors>
<globalization>
<pages>
<processModel>
<sessionState>
<trace>
Let's take a look at each section in more detail.
authentication
The authentication section provides configuration settings for how authentication is performed in the ASP.NET environment.
The required mode attribute specifies the default authentication mode for the application. The mode attribute supports the following values:
WindowsWindows authentication is used. Use this mode if you're using any form of IIS authentication: Basic, Digest, Integrated Windows Authentication (NTLM/Kerberos), or certificates.
FormsASP.NET forms authentication is used. This authentication mode occurs when application-specified credentials are used rather than server-level authentication, such as Windows NT accounts.
PassportMicrosoft Passport is used.
NoneNo authentication support is provided.
The authentication section also supports the forms and passport child elements.
forms
The forms element specifies the configuration for an application using forms-based authentication. Table 7.2 lists the attributes of the forms element.
Table 7.2 Attributes of the forms Element
Attribute Name |
Description |
name |
(Required). Specifies the HTTP cookie to use for authentication. The default value is .ASPXAUTH. You must configure the cookie name for each application on a server requiring a unique cookie in each application's web.config file. |
loginUrl |
Specifies the URL to redirect the user to if no valid authentication cookie is found. The default value is default.aspx. |
protection |
Specifies how the cookie is protected. The valid values are the following:
|
timeout |
The number of minutes since the last request received, after which the authentication cookie expires. (The default is 30 minutes.) |
path |
The path used for cookies issued by the application. (The default is \.) |
The forms element supports the credentials subelement that contains the user IDs and associated passwords, as well as how the passwords as encrypted. The credentials element supports a single attribute, passwordFormat, which describes the password encryption algorithm used. The passwordFormat attribute supports the following values:
ClearNo encryption is performed on the password. The password is stored as clear text.
MD5The password has been encrypted using the MD5 hash algorithm. The user's password is encrypted and the hashed values are compared to determine authentication.
SHA1The password has been encrypted using the SHA1 hash algorithm. The user's password is encrypted and the result is compared to the stored password hash value.
The credentials element supports a child element, user, which stores the name of the user and the password using the encryption technique specified by the passwordFormat attribute. The user element supports two attributes:
nameThe user ID of an authorized user of the system.
passwordThe password encrypted using the algorithm specified in the passwordFormat attribute.
passport
The passport element configures authentication by using Microsoft Passport. It supports a single attribute, redirectUrl. This attribute specifies the login page where the user is redirected if he or she hasn't signed on with Passport authentication. (The default redirect URL is default.aspx.)
authorization
The authorization element specifies client access to URL resources by explicitly allowing or denying user access to a specific resource. This is done through the allow and deny subelements. These elements share the same attributes and possible values:
usersComma separated list of users. A question mark (?) is used for anonymous users and an asterisk (*) denotes all users.
rolesComma separated list of roles explicitly allowed or denied access to the URL resource.
verbsComma separated list of HTTP transmission methods that are allowed or denied access to the resource (GET, POST, HEAD, and DEBUG).
Recall that settings are inherited from the machine.config file unless they're overridden. The default value in the machine.config file is the following:
<allow users="*"/>
This implies that all users are authorized for a URL resource unless otherwise configured. The sample web.config file in Listing 7.2 shows how to use forms authentication that denies unauthenticated users to the URL resource.
Listing 7.2 Sample web.config File that Uses Forms Authentication and Denies Unauthenticated Users
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <authentication mode="Forms"> <forms loginUrl="/sitelogin.aspx">
<credentialspasswordFormat="Clear"> <user name="deanna"password="wife"/> <user name="lilbit"password="son"/> <user name="teenybit"password="unborn"/> </credentials> </forms> </authentication> <authorization> <allow users="Users" /> <deny users="?" /> </authorization> </system.web> </configuration>
browserCaps
The browserCaps element controls the settings for the browser capabilities component. The browser capabilities component is similar to its predecessor, browscap.ini, which determines capabilities of browsers based on their User_Agent header value.
By defining new browser capabilities within this section, you can take advantage of newly released browsers and their capabilities. The browserCaps element supports three child elements: filter, result, and use.
filter
The filter element evaluates the case child element to evaluate the first rule to be applied.
The filter element supports the following optional attributes:
matchA regular expression tested against the value resulting from the expression in the with attribute.
withA regular expression or string to be searched. If this attribute is not present, the value in the use element is used.
In case multiple rules need to be evaluated, the filter element also supports the child case element, which supports the match and with elements to provide conditional rule processing where only the first match is evaluated.
result
The result element specifies the HttpCapabilitiesBase, which is a derived class that holds the results from parsing this section. This element supports a single attribute called Type. Type represents the fully qualified name of the class responsible for parsing the section and providing the results.
use
The use element specifies the server variables that evaluates the filter and case statements in this section and the value assignments.
The use element supports two optional attributes:
varThe IIS server variable that is parsed to evaluate browser compatibility settings. The default is HTTP_USER_AGENT.
asA name that can be referenced in the child filter and case elements, as well as in variable expressions and assignments.
A Browser Capabilities Example
Listing 7.3 shows an example of how to define settings in the browserCap section of the web.config file that parses the HTTP_USER_AGENT server variable to determine the various browsers' capabilities. Here's an example of the HTTP_USER_AGENT server variable string:
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.2914)
Listing 7.3 Sample web.config File Showing the browserCaps Section and Nested Filters
<?xml version="1.0" encoding="UTF-8" ?> <configuration> <system.web> <browserCaps> <result type="System.Web.HttpBrowserCapabilities" /> <use var="HTTP_USER_AGENT" /> browser=Unknown version=0.0 majorversion=0 minorversion=0 frames=false tables=false cookies=false backgroundsounds=false vbscript=false javascript=false javaapplets=false activexcontrols=false win16=false win32=false beta=false ak=false sk=false aol=false crawler=false cdf=false gold=false authenticodeupdate=false tagwriter=System.Web.UI.Html32TextWriter ecmascriptversion=0.0 msdomversion=0.0 w3cdomversion=0.0 platform=Unknown clrVersion=0.0 css1=false css2=false xml=false <filter> <case match="COM\+|\.NET CLR (?'clrVersion'[0-9\.]*)"> clrVersion=${clrVersion} </case> </filter> <filter> <case match="^Microsoft Pocket Internet Explorer/0.6"> browser=PIE version=1.0 majorversion=1 minorversion=0 tables=true backgroundsounds=true platform=WinCE </case> <case match="^Mozilla[^(]*\(compatible; MSIE
(?'version'(?'major'\d+)(?'minor'\.\d+)(?'letters'\w*))(?'extra'.*)"> browser=IE version=${version} majorversion=${major} minorversion=${minor} <case match="[5-9]\." with="${version}"> frames=true tables=true cookies=true backgroundsounds=true vbscript=true javascript=true javaapplets=true activexcontrols=true tagwriter=System.Web.UI.HtmlTextWriter ecmascriptversion=1.2 msdomversion=${major}${minor} w3cdomversion=1.0 css1=true css2=true xml=true <filter with="${letters}" match="^b"> beta=true </filter> </case> </case> </filter> </browserCaps> </system.web> </configuration>
The example in Listing 7.3 begins by defining the default browser capabilities. By default, you can assume that no features are supported, so you can set numeric values to 0 and Boolean values to false. Evaluate the HTTP_USER_AGENT string and turn capabilities as you see that they are supported. The HTTP_USER_AGENT string value is then parsed and applied to any filters that are present.
The first filter (using the regular expression COM\+|\.NET CLR (?'clrVersion'[0-9\.]*)) parses the string to see if the client has the .NET Common Language Run-time (CLR) installed; if it does, it assigns the CLR version to the browser capability property, clrVersion.
The second filter uses the regular expression, ^Microsoft Pocket Internet Explorer/0.6, to see if the browser is a mobile device running Microsoft Pocket Internet Explorer. If a match occurs, the only supported attributes for the browser are tables and background sounds. Cookies, VBScript, JavaScript, JavaApplets, and other browser functions are not supported.
The third filter uses a long and complex regular expression:
^Mozilla[^(]*\(compatible; MSIE (?'version'(?'major'\d+) (?'minor'\.\d+)(?'letters'\w*))(?'extra'.*)
In effect, this regular expression looks to see if the HTTP_USER_AGENT string contains the string Mozilla(compatible; MSIE. If the substring is found, the major version, minor version, and any trailing letters are stored in the major, minor, and letters variables, respectively. So, given this HTTP_USER_AGENT string,
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.2914)
the variables would be populated as
versionMSIE 6.0
major6
minor0
letters{empty}
Now that you understand how to define browser capabilities and why you'd want to do this, look at how you can leverage the browserCaps section in the ASP.NET and XML code.
Recall that the result element defined the type of object that is returned from interrogating browser capabilities. The type of object must be derived from the HttpCapabilitiesBase class, which is found in the System.Web.Configuration namespace. This class provides the various properties needed to interrogate the browser's capabilities. The HttpBrowserCapabilities class in the System.Web namespace derives from this class, so you'll need to use this class to interrogate the class' properties.
Listing 7.4 demonstrates the use of the HttpBrowserCapabilities class to detect the browser version and apply the appropriate XSLT stylesheet. Note the use of the Browser property to determine if the browser is IE compatible.
Listing 7.4 Sample Application to Determine Browser Capabilities
<%@ Import Namespace="System.Web.Configuration"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <title>Browscap Demo</title> <script language="vb" runat="server"> Private Sub Page_Load(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MyBase.Load Dim browsCap As HttpBrowserCapabilities browsCap = Request.Browser Xml1.DocumentSource = "source.xml" If browsCap.Browser = "IE" Then Xml1.TransformSource = "ie.xslt" Else Xml1.TransformSource = "non_ie.xslt" End If End Sub </script> </HEAD> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <asp:Xml id="Xml1" runat="server"></asp:Xml></TD> </form> </body> </HTML>
Besides the browser's name, other properties can be determined by using the HttpBrowserCapabilities class. These properties are discussed in the section, "System.Configuration and System.Web.Configuration Namespaces."
compilation
The compilation section configures how ASP.NET compiles the application. Table 7.3 shows the acceptable attributes of the compilation section.
Table 7.3 Attributes of the compilation Section
Attribute Name |
Description |
debug |
Indicates if the debug version of the code needs to be compiled. The default is false. |
defaultLanguage |
Specifies the default language to use in dynamic compilation files. The default is vb. |
explicit |
Specifies the Visual Basic explicit compile option, requiring variable declaration when enabled. The default is true. |
batch |
Indicates if batching is supported. |
batchTimeout |
The time-out period, in seconds, for batch compilation. |
maxBatchGeneratedFileSize |
The maximum size (KB) of the generated source files per batched compile. |
maxBatchFileSize |
The maximum number of pages per batch compile. |
numRecompilesBeforeApprestart |
The number of dynamic recompiles before the application is restarted. |
strict |
Specifies the Visual Basic strict compile option, where only widening implicit conversions are allowed. (For example, long to integer is disallowed, but integer to long is okay.) |
tempDirectory |
Specifies the temporary directory used for compilation. |
customErrors
The customErrors element supports custom error messages for an ASP.NET application. It specifies if custom error messages are enabled and custom redirect pages are associated with an HTTP status code, as well as if custom error messages are visible to local developers.
The required mode attribute specifies how custom error messages are handled and supports the following values:
OnCustom error messages are enabled.
OffCustom error messages are disabled and detailed errors are displayed.
RemoteOnlyCustom error messages are shown to remote clients only; the local host still receives detailed error messages.
The optional defaultRedirect attribute specifies the default URL to redirect to if an error occur.
The error subelement defines the error page that's associated with an HTTP status code. It supports the following attributes:
statusCodeThe HTTP status code that causes the display of the redirect page.
redirectThe page to redirect to as a result of the HTTP status code.
globalization
The globalization element supports encoding attributes for globalization of the application. The globalization element supports the attributes shown in Table 7.4.
Table 7.4 Attributes of the globalization Element
Attribute Name |
Description |
culture |
The default culture for processing incoming requests. Valid values are ISO 639 country codes and subcodes (en-US and en-GB). |
uiCulture |
The default culture for processing locale-dependent resource searched. Valid values are ISO 639 country codes and subcodes. |
requestEncoding |
Specifies the assumed encoding of the incoming request. If request encoding is not specified, the locale of the server is used. (The default is UTF-8.) |
responseEncoding |
Specifies the content encoding of responses. (The default is UTF-8.) |
fileEncoding |
Specifies the default encoding for .aspx, .asmx, and .asax file parsing. |
identity
The identity element specifies if impersonation is used for the application. It supports the following required attributes:
impersonateClient impersonation is used.
userNameThe username to use if impersonation is used.
password The password to use if impersonation is used.
pages
The pages element controls page-specific configuration settings. Table 7.5 shows the optional attributes of the pages section.
Table 7.5 Optional Attributes of the pages Element
Attribute Name |
Description |
autoEventWireup |
Indicates if page events are automatically enabled. |
buffer |
Specifies if response buffering is used. |
enableSessionState |
Indicates if session state handling is enabled. The following values are accepted:
|
enableViewState |
Indicates if the page and its controls should persist view state after page processing is complete. |
pageBaseType |
Specifies a code-behind class that .aspx pages inherit from by default. |
smartNavigation |
Indicates if IE 5.0 smart history navigation is enabled. |
userControlBaseType |
Specifies a code-behind class that user-control inherits from by default. |
processModel
The processModel element represents a process model configuration for the IIS web server. The processModel element supports the following optional attributes, as shown in Table 7.6.
Table 7.6 Optional Attributes of the processModel Element
Attribute Name |
Description |
clientConnectedCheck |
How long a request is left in the queue until IIS performs a check to see if the client is still connected. |
comAuthenticationLevel |
Indicates the level of DCOM security. |
comImpersonationLevel |
Specifies the authentication level for DCOM security. |
cpuMask |
Defines what CPUs on a multiprocessor server are eligible to run ASP.NET processes. |
enable |
Indicates if this process model is enabled. |
idleTimeout |
Specifies the period of inactivity after which ASP.NET ends the worker process. |
logLevel |
Specifies event types to be logged to the event log. |
maxWorkerThreads |
The maximum number of threads to be allocated on a per CPU basis. |
maxIoThreads |
The maximum number of threads to be allocated on a per CPU basis. |
memoryLimit |
The maximum percentage of total system memory before ASP.NET launches a new worker process and enqueues existing processes. |
password |
Specifies the worker process to run as the specified username with the specified password. |
pingFrequency |
The time interval at which ASP.NET pings the worker process to see if it is still running. |
pingTimeout |
The time after which a nonresponsive worker process is restarted. |
requestLimit |
The number of requests allowed before a new process is spawned to replace the current one. |
requestQueueLimit |
Specifies the number of requests allowed in the queue before ASP.NET begins returning 503Server Too Busy errors to new requests. The default is 5,000. |
serverErrorMessageFile |
Specifies the file to use in place of the Server Unavailable message. |
shutdownTimeout |
The number of minutes the worker process is allowed to shut itself down. |
timeout |
Number of minutes before a new process is spawned to replace the current one. |
userName |
Specifies the worker process to run as the specified username with the specified password. |
webGarden |
Controls CPU affinity. |
sessionState
The sessionState section controls how session management is handled in the application. The sessionState element requires a mode attribute that supports the following values:
InprocSession state is stored locally in memory (in process).
StateServerSession state is stored on a remote server.
SQLServerSession state is stored on the specified SQL Server.
OffSession state is disabled.
The optional attributes shown in Table 7.7 are also supported by the sessionState element.
Table 7.7 Optional Attributes of the sessionState Element
Attribute Name |
Description |
cookieless |
Indicates if sessions without cookies are used. If cookies are not used, an identifier is used in the querystring. |
timeout |
The number of minutes a session can be idle before it times out. |
stateConnectionString |
Specifies the address of the remote server when the mode is StateServer. |
sqlConnectionString |
Specifies the SQL connection string to use when the mode is SQLServer. |
trace
The trace section configures the ASP.NET trace service. The optional attributes, shown in Table 7.8, are supported.
Table 7.8 Optional Attributes of the trace Element
Attribute Name |
Description |
enabled |
Indicates if tracing is enabled for an application. This setting can be overridden at the page level. |
localOnly |
Specifies that only the local host can see trace information. |
pageOutput |
Specifies if trace information is included with each page output. If false, trace information is viewable only through the trace viewer trace.axd. |
requestLimit |
The number of trace requests to store on the server. If the limit is reached, trace is automatically disabled. |
traceMode |
Indicates how tracing information is to be sorted. Supports the following values:
|