<configuration> |
    <configuration>
    </configuration>
The root element for all configuration files; it is required.
Scope
All
Attributes
None

<appSettings> |
    <appSettings>
    </appSettings>
The <appSettings> element can be used to configure custom application settings as key/value pairs. These settings can later be retrieved at runtime using the AppSettings property of the ConfigurationSettings class, as shown in the example. This property is shared (static) and does not require the ConfigurationSettings class to be instantiated before accessing the property.
Scope
Any
Attributes
None
Child Elements <add> The pattern to match. <remove> The pattern to match. <clear> The pattern to match.
Example
The following web.config section sets an application level key/value pair:
    <configuration>
    	<appSettings>
    		<add key="applicationConfigKey" value="bar"/>
    	</appSettings>
    </configuration>
The following ASP.NET page retrieves the value set by the preceding code and also retrieves a value set at the machine.config level:
    <%@ Page Language="VB" %>
    <html>
    	<head>
    		<script runat="server">
    			Sub Page_Load( )
    				Message1.Text &= _
    				ConfigurationSettings.AppSettings("machineConfigKey")
    				Message2.Text &= _
    				ConfigurationSettings.AppSettings("applicationConfigKey")
    			End Sub
    		</script>
    	</head>
    <body>
    	<asp:label id="Message1" runat="server">
    		Machine.Config setting:
    	</asp:label><br/>
    	<asp:label id="Message2" runat="server">
    		Web.Config setting:
    	</asp:label>
    </body>
    </html>
Notes
As shown in the example, the <appSettings> element can be used separately from the <system.web> element and its children.
For security reasons, use caution when deciding what kinds of data to store using the <appSettings> element. Remember that while the ASP.NET runtime is set up to prevent an application's web.config file from being requested or read, this file could still be vulnerable if the security of the web server were breached in some other way. Thus, you should generally avoid storing sensitive information such as usernames and passwords, or connection strings containing usernames and passwords, in the web.config file. A better, although still moderately vulnerable, alternative is to store this information at the machine.config level, since this file is not within the web space of the application and is not as vulnerable to compromise through attacks on IIS. However, remember that this information will be available to any application on the machine.

<system.web> |
    <system.web>
    </system.web>
Container element for all elements used in web.config files.
Scope
All
Attributes
None
Child Elements
<authentication>, <authorization>, <browserCaps>, <clientTarget>, <compilation>, <customErrors>, <globalization>, <httpHandlers>, <httpModules>, <httpRuntime>, <identity>, <iisFilter>, <machineKey>, <pages>, <processModel>, <securityPolicy>, <sessionState>, <trace>, <trust>, <webServices>
Notes
This element is required in order to use any of its child elements.

<authentication> |
    <authentication>
    </authentication>
Provides attributes and contains child elements used to configure authentication options in ASP.NET.
Scope
Machine, Application
Attributes Mode Determines the type of authentication that will be used by ASP.NET. Valid values are: Windows(default) Uses credentials provided by IIS authentication methods (Basic, Digest, Integrated Windows Authentication, or Certificates) to authenticate user requests. Requests can then be permitted or denied based on settings contained within the <authorization> element, using the authenticated username (or an associated group/role name) to allow or deny the request. This is the default authentication mode defined in machine.config. Forms Provides an infrastructure for performing custom authentication in situations when Windows authentication is not possible. When Forms authentication is enabled, users who have not logged in are automatically redirected to a login URL provided as an attribute of the <forms> element. Once logged in, a cookie is sent as an authentication token. Users can be authenticated against any credentials database the developer chooses -- from Active Directory to a custom credentials database. This mode requires the inclusion of the <forms> child element. Passport Takes advantage of Microsoft's Passport authentication service. This mode requires inclusion of the <passport> child element. None Specifies that no authentication be performed at the ASP.NET level. Requests can still be authenticated at the IIS level using one of the IIS authentication modes in combination with NTFS access control lists (ACLs).
Child Elements
<forms>, <passport>
Example
The example configures the pages within the scope of the configuration file to use ASP.NET forms-based authentication:
    <configuration>
    	<system.web>
    		<authentication mode="Forms">
    			<forms name="myAuthCookie" loginUrl="login.aspx"
    			protection="All" timeout="30"path="/" />
    		</authentication>
    	</system.web>
    </configuration>
Notes
The <location> element can be used to configure authentication at the machine level, if desired, and its allowOverride attribute can be used to prevent overriding these settings in individual applications.
Authentication can be a fairly involved topic. For more information on the various ASP.NET authentication methods and how they relate to IIS authentication, please see Chapter 9.

<forms> |
    <forms
    	 loginUrl=String
    	 name=String
    	 path=String protection="All|None|Encryption|Validation"
    	 timeout=Integer>
    </forms>
Provides attributes and one child element (<credentials>) to configure ASP.NET to use forms-based authentication.
Scope
Machine, Application
Attributes name Specifies the name of the authentication cookie. If this attribute is omitted, the value defaults to .ASPXAUTH. When running multiple applications that use forms-based authentication on the same server, it's usually a good idea to give each application its own authentication cookie name -- to minimize the risk of authenticated users from one application being treated as authenticated in others. loginUrl Specifies the redirect URL for users who do not have a valid authentication cookie. If a user with no authentication cookie requests a page in the application, they will be redirected to this URL to log in. The login page can then redirect the user back to the originally requested page. If this attribute is omitted, the value defaults to login.aspx. protection Specifies the type of protection used to prevent the authentication cookie from being modified during transit.Valid values are: All Cookies are both encrypted (using triple DES encryption, if available) and subjected to data validation. Data validation is performed based on the settings of the machineKey element. All is the default value and is the recommended setting for securing the authentication cookie. Encryption Cookies are only encrypted. This reduces overhead associated with cookie protection, but may leave cookies vulnerable to plain-text attacks. None Neither encryption nor validation is enabled for cookie protection. This reduces overhead when using forms-based authentication, but provides no protection of the authentication cookie. This attribute is not recommended. Validation A validation key is concatenated with cookie data. This key is checked to ensure that cookie data has not been altered in transit. timeout Specifies the amount of time, in minutes, before the authentication cookie expires. This is a sliding value, which is reset when a request is received after more than half of the timeout period has elapsed. Note that this attribute does not apply to persistent cookies. The default value is 30. path Specifies the path for the authentication cookie. Because many browsers treat the path in a case-sensitive manner, the default is set to the backslash (\) character.
Child Elements
<credentials>
Example
See the example for the <authentication> element.
Notes
Forms-based authentication is only effective when used in conjunction with the <authorization> element to deny anonymous users access to pages within the application.
It's a good idea to use SSL encryption to protect the forms authentication credentials and cookie to prevent the possibility of these credentials being hijacked. If you can't (or don't want to) use SSL, you should at least reduce the default timeout value to lessen the likelihood of someone capturing and impersonating the authentication cookie.

<credentials> |
    <credentials
    		passwordFormat="Clear|SHA1|MD5">
    </credentials>
Allows you to store one or more sets of credentials in the application (or machine) configuration file for later use in authenticating requests. The child <user> element is used to store the actual credentials.
Scope
Machine, Application
Attributes passwordFormat Specifies the format in which passwords will be stored (and compared). Valid options are Clear, SHA1, and MD5.
Child Elements
<user>
Example
The example shows the <credentials> element, which is used to store two user accounts to authenticate against:
    <credentials passwordFormat = "SHA1">
    	<user  name="foo" password="794ED3D18464BAFF93F8DED1CFD00D9A2D9FE316"/>
    	<user  name="bar" password="B7CDD2A2B0F05E6948E5CEED22FA9A38EB28DEC8"/>
    </credentials>
Notes
Once you've stored the credentials, you can authenticate against them by calling the static (shared) Authenticate method of the FormsAuthentication helper class. You can use the static (shared) HashPasswordForStoringInConfigFile method of FormsAuthentication to create an MD5 or SHA1 hash of the password for storing in the <user> element. When using the <credentials> element to store credentials, you should always hash passwords, since storing them in readable text presents a potential security risk. Although theoretically, no one should be able to read the configuration file, a server misconfiguration or security vulnerability could conceivably expose this file.

<user> |
<user> |
Store the username and password for each user defined in the <credentials> element.
Scope
Machine, Application
Attributes name The username to be authenticated against. password The password to be authenticated against.
Child Elements
None
Example
See the example for the <credentials> element.
Notes
You should always use the HashPasswordForStoringInConfigFile method to hash passwords stored in the password attribute. A utility page that creates SHA1 or MD5 hashes of plain text passwords is provided in the examples for Chapter 9.

<passport> |
<passport redirectUrl=Url /> |
This optional element configures an internal URL to which unauthenticated requests will be redirected when using Microsoft's Passport authentication provider. This element should be used only when the <authentication> element's mode attribute is set to Passport.
Scope
Machine, Application
Attributes redirectUrl A URL in the application to which requests lacking a Passport authentication token are redirected.
Child Elements
None
Example
This example shows a web.config file that configures an application for Passport authentication:
    <configuration>
    	<system.web>
    		<authentication mode="Passport">
    			<passport redirectUrl="Login.aspx"/>
    		</authentication>
    	</system.web>
    </configuration>
Notes
For more information on configuring Passport authentication, see the Passport SDK documentation, which is available from http://www.passport.com.

<authorization> |
Provides two child elements, <allow> and <deny>, that allow you to configure the users, roles, or HTTP verbs that can be used to access application resources.
Scope
Any
Attributes
None
Child Elements
<allow>, <deny>
Example
The example allows users Mary and John to access application resources using any HTTP verb, while denying POST access to nonauthenticated users:
    <configuration>
    	<system.web>
    		<authorization>
    			<allow  users="Mary, John" />
    			<deny users="?" verbs="POST" />
    		</authorization>
    	</system.web>
    </configuration>
Notes
The type of authorization implemented by the <authorization> element is referred to as URL authorization. You can read more about URL authorization in Chapter 9.
You can specify authorization settings for a specific file or directory in your application that differs from the defaults configured in the root web.config file for the application in either of two ways: By adding an <authorization> element to the web.config file of the desired child directory, as shown in the example. By using a <location> tag in the root web.config file and setting its path attribute to the desired path, as follows:
    <configuration>
    	<location path="files">
    		<system.web>
    			<authorization>
    				<deny users="?" />
    			</authorization>
    		</system.web>
    	</location>
    	<system.web>
    		<!--other configuration settings -->
    	</system.web>
    </configuration>

<allow> |
Specifies users, roles, and/or HTTP verbs to be authorized for the application.
Scope
Any
Attributes users A comma-delimited list of authorized usernames. roles A comma-delimited list of authorized roles (NT groups). verbs A comma-delimited list of authorized HTTP verbs (GET, HEAD, POST, or DEBUG).
Child Elements
None
Example
See the example for the <authorization> element.
Notes
You can use two wildcards to specify special groups of users: * When used for the value of the user attribute, allows access for all users. This is the default configuration setting, as defined in machine.config. ? When used for the value of the user attribute, allows access to anonymous users. This wildcard is more commonly used with the <deny> element.

<deny> |
Specifies users, roles, and/or HTTP verbs to be denied authorization for the application.
Scope
Any
Attributes users A comma-delimited list of authorized usernames. roles A comma-delimited list of authorized roles (NT groups). verbs A comma-delimited list of authorized HTTP verbs (GET, HEAD, POST, or DEBUG).
Child Elements
None
Example
See the example for the <authorization> element.
Notes
The same wildcards used by the <allow> element also apply to the deny element. To deny access to anonymous (non-authenticated) users, set the value of the users attribute of the <deny> element to ?.

<browserCaps> |
    <browserCaps>
    		<result type=className />
    		<use var=serverVarName />
    				property1=value
    				property2=value
    				propertyN=value
    		<filter match=string>
    				property1=value
    				property2=value
    				propertyN=value
    		</filter>
    		<filter match=string>
    			<filter match=string with=expressionToSearch>
    				property1=value
    				property2=value
    				propertyN=value
    			</filter>
    		</filter>
    		<filter>
    			<case match=string>
    				property1=value
    				property2=value
    				propertyN=value
    			</case>
    			<case match=string>
    				property1=value
    				property2=value
    				propertyN=value
    			</case>
    		</filter>
    </browserCaps>
Controls the configuration of the browser capabilities component returned by the Response.Browser property. The property/value pairs under the <use> element configure the default values of the browser capabilities component properties; the property/value pairs in the <filter> elements update these properties based on a match between the string value specified for the match attribute of the <case> element and the value of the var attribute of the <use> element (which is typically set to HTTP_USER_AGENT).
Scope
Any
Attributes
None
Child Elements
<result>, <use>, <filter>
Example
The machine.config configuration file contains the default settings for the <browserCaps> element. The default settings provide the best example for modifying or updating this element.
Notes
The primary purpose of this configuration element and its children is to allow the addition of new browser types and updating the capabilities of these browsers. Thus, when a page calls the browser capabilities component, it will receive accurate information about the capabilities of the browser used for the current request.

<result> |
<result type=className /> |
Specifies the class.
Scope
Any
Attributes type The class name, and optionally, version, culture, and key information that specifies the class that will contain the results of the browser capabilities analysis. This class must derive from HttpCapabilitiesBase. The default (set in machine.config) is System.Web.HttpBrowserCapabilities.
Child Elements
None
Notes
The default type of System.Web.HttpBrowserCapabilities is fine in most cases. If you want to add additional properties beyond those defined by the HttpBrowserCapabilities class, you can create your own class (derived from HttpCapabilitiesBase or HttpBrowserCapabilities) and use the <result> element to substitute it.

<use> |
<use var=serverVariableName as=aliasName /> |
Sets the name of the server variable to use when evaluating browser capabilities.
Scope
Any
Attributes var The name of the server variable to use. The default is HTTP_USER_AGENT. as The string containing a name by which the server variable can be referenced in <case> elements and regular expressions.
Child Elements
None
Notes
The <use> element is followed by property/value pairs that specify the default properties for the browser capabilities component if no match is found with a <filter> element's match attribute (or that of its child <case> element). This usage is demonstrated in the entry for the <browserCaps> element.

<filter> |
    <filter match=string>
    		property1=value
    		property2=value
    		propertyN=value
    </filter>
    < filter match=string>
    		<filter match=string with=expressionToSearch>
    				property1=value
    				property2=value
    				propertyN=value
    		</filter>
    </filter>
    < filter>
    		<case match=string>
    				property1=value
    				property2=value
    				propertyN=value
    		</case>
    		<case match=string>
    				property1=value
    				property2=value
    				propertyN=value
    		</case>
    </filter>
Specifies a regular expression pattern to search for in the server variable given in the <use> element (or optionally, another expression). Multiple <filter> elements can be contained in the <browserCaps> element; likewise, each <filter> element can contain <case> elements or other <filter> elements. All property assignments for matching <filter> elements will be executed, regardless of their order.
Scope
Any
Attributes match The pattern to match. Uses .NET Framework regular expression syntax. This attribute is optional. If omitted, all requests will be assumed to match and any property/value assignments contained within the <filter> element will be executed. with The regular expression or string to search for. This attribute is optional. If omitted, the server variable specified in the <use> element will be searched.
Child Elements
<case>
Notes
The fact that <filter> elements can be nested makes them very flexible in terms of locating subsets of information. For example, the default <browserCaps> element in machine.config uses nested <filter> elements to locate both the major and minor browser versions contained in the HTTP_USER_AGENT server variable so that it can assign specific properties that vary among minor versions (i.e., the x in 4.x) of a browser.

<case> |
    <case match=string>
    		property1=value
    		property2=value
    		propertyN=value
    </case>
Specifies one of a group of exclusive matching cases for which property assignments will be executed. Only the first matching <case> element within a given <filter> element will be executed. The rest will be ignored.
Scope
Any
Attributes match The pattern to match. Uses the .NET Framework regular expression syntax. This attribute is optional. If omitted, all requests will be assumed to match, and any property/value assignments contained within the <filter> element will be executed. with The regular expression or string to search for. This attribute is optional. If omitted, the server variable specified in the <use> element will be searched.
Child Elements
None
Notes
This element is useful in situations when you only want a single match. For example, the default <browserCaps> configuration in machine.config uses the <case> element to assign the platform, win16, and win32 attributes.

<clientTarget> |
    <clientTarget>
    		<add alias=aliasName
    				userAgent=userAgentString />
    		<remove alias=aliasName />
    		<clear />
    </clientTarget>
Assigns aliases for specified browser user agent strings to be used by ASP.NET Server Controls in deciding what type of content to render.
Scope
Any
Attributes
None
Child Elements <add> Adds an alias with the name specified by the alias attribute for the User Agent string specified by the userAgent attribute. <remove> Removes a previously configured alias with the name specified by the alias attribute. <clear> Clears all previously configured aliases.
Example
This example comes from the default <clientTarget> element:
    <clientTarget>
    	<add alias="ie5" userAgent="Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)" />
    	<add alias="ie4" userAgent="Mozilla/4.0 (compatible; MSIE 4.0; Windows NT 4.0)" />
    	<add alias="uplevel" userAgent="Mozilla/4.0 (compatible; MSIE 4.0; Windows NT 4.0)" />
    	<add alias="downlevel" userAgent="Unknown" />
    </clientTarget>
Notes
This element is used primarily by the built-in ASP.NET Server Controls. Thus, you should avoid making changes to the existing aliases to avoid preventing these controls from rendering uplevel content.

<compilation> |
    <compilation
    		batch=boolean
    		batchTimeout=numSeconds
    		debug=boolean
    		defaultLanguage=languageAlias
    		explicit=boolean
    		maxBatchSize=maxPages
    		maxBatchGeneratedFileSize=maxSize
    		numRecompilesBeforeAppRestart=numRecompiles
    		strict=boolean
    		tempDirectory=dirName >
    		<compilers>
    			<compiler language=languageAlias
    					extension=fileExt
    					type=typeName
    					warningLevel=number
    					compilerOptions=optionString />
    		</compilers>
    		<assemblies>
    			<add assembly=assemblyName />
    			<remove assembly=assemblyName />
    			<clear />
    		</assemblies>
    </compilation>
Provides attributes and child elements for configuring the compilation options of ASP.NET applications. All attributes are optional.
Scope
Any
Attributes batch Specifies whether ASP.NET should attempt to batch compile all pages in the application when the first request for a page is made. The default is True. batchtimeout Specifies the amount of time, in seconds, that the compiler will spend attempting to batch compile pages in the application. If the timeout is exceeded, pages will be compiled as they are requested for the first time. The default is 15. debug Specifies whether pages will be compiled with debug symbols. The default is False. defaultLanguage Specifies the language compiler that will be used to compile inline code in ASP.NET pages for which no language is specified. The default is VB (Visual Basic .NET). explicit Specifies whether the Visual Basic .NET OptionExplicit compiler option is enabled. The default is True. maxBatchSize Specifies the maximum number of classes generated during batch compilation. The default is 1000. maxBatchGeneratedFileSize Specifies the maximum combined size in KB of generated source files created during batch compilation. The default is 3000. numRecompilesBeforeAppRestart Specifies the number of recompiles before the appDomain containing the application is cycled (a new appDomain is created and the old one is torn down). The default is 15. strict Specifies whether the Visual Basic .NET OptionStrict compiler option (which disallows implicit narrowing conversions) is enabled. The default is False. tempDirectory Specifies the directory in which temporary files from dynamically compiled code for the application will be stored. The default is %windir%\Microsoft.NET\Framework\%version%\Temporary ASP.NET Files.
Child Elements
<assemblies>, <compilers>
Example
The example enables the Visual Basic .NET OptionStrict compiler option and disables batch compilation:
    <configuration>
    	<system.web>
    		<compilation batch="false" strict="true">
    		</compilation>
    	</system.web>
    </configuration>
Notes
Make sure you understand the impact of changes to this element before making modifications. For example, setting the debug attribute to True will have a significant negative impact on performance. While setting the strict attribute to True will reduce the likelihood of bugs from implicit data type conversion, it could also increase the number of compiler errors you get while developing your code.

<assemblies> |
    <assemblies>
    		<add assembly=assemblyInfo />
    		<remove assembly=assemblyInfo />
    		<clear />
    </assemblies>
Adds or removes assemblies to be referenced and linked during dynamic compilation of ASP.NET pages. By default, the mscorlib, System, System.Drawing, System.EnterpriseServices, System.Web, System.Data, System.Web.Services, and System.Xml assemblies are referenced during dynamic compilation, as are any assemblies located in the application directory's bin subdirectory.
Scope
Any
Attributes
None
Child Elements <add> Adds an assembly specified by the assembly attribute to the list of assemblies to be linked during dynamic resource compilation. <remove> Removes a previously configured assembly specified by the assembly attribute from the list of assemblies to be linked during dynamic resource compilation. <clear> Clears all previously configured assemblies.
Example
This example shows the <add> element used by the Mobile Internet Toolkit to add the assembly System.Web.Mobile to the list of assemblies for dynamic compilation:
    <assemblies>
    	<add assembly="System.Web.Mobile,Version=1.0.3300.0,Culture= _
    	neutral PublicKeyToken=b03f5f7f11d50a3a" />
    </assemblies>
Notes
The asterisk (*) wildcard is used with the <add> element to indicate that all assemblies in the application's private assembly cache (by default, the bin subdirectory of the application) should be added to the list of assemblies linked during dynamic compilation. This ensures that all members of these assemblies will be available to all the pages in your application automatically.

<compilers> |
    <compilers>
    	<compiler language=languageAlias
    		extension=fileExt
    		type=typeName
    		warningLevel=number
    		compilerOptions=optionString />
    </compilers>
Contains one or more <compiler> elements, each of which defines configuration options for a particular compiler to be used with ASP.NET.
Scope
Any
Attributes
None
Child Elements
<compiler>
Notes
Thanks to the <compilers> and <compiler> elements, adding support for a new .NET language in ASP.NET is as simple as adding a new <compiler> element specifying the language aliases, the file extension for class files for the language, and the type information for the language compiler.

<compiler> |
    <compiler language=languageAlias
    		extension=fileExt
    		type=typeName
    		warningLevel=number
    		compilerOptions=optionString />
Specifies configuration options for a given language.
Scope
Any
Attributes language Specifies the name or names by which the language will be specified in the language attribute of the @Page directive. Multiple names should be separated by semicolons. This attribute is required. extension Specifies the extension(s) used by code-behind files for the specified language. Multiple entries should be separated by semicolons. This attribute is required. type Specifies the .NET type information for the class to be used to compile resources for the specified language. This attribute is required. warningLevel Specifies the compiler warning level for the language. This attribute is optional and may not be supported for all compilers. CompilerOptions Specifies a string containing valid compiler options to be passed to the compiler.
Child Elements
None
Notes
The <compilers> element in machine.config provides a good example of the use of this element. Review that configuration section to see how the Visual Basic .NET, C#, and JScript .NET compilers are configured.

<customErrors> |
    <customErrors
    	defaultRedirect=Url
    	mode=mode >
    	<error statusCode=httpStatusCode redirect=Url />
    </customErrors>
Specifies one or more pages to which users should be redirected if an unhandled exception is detected in an ASP.NET application. A default error page can be specified, as well as one or more error pages for specific HTTP error codes.
Scope
Any
Attributes defaultRedirect Specifies the URL of the page to which all errors should be redirected when no specific error page is configured for the HTTP status code of the error. This attribute is optional. mode Specifies the custom errors mode. Valid values are Off, On, and RemoteOnly. Off disables custom error handling, On enables custom error pages for both local and remote requests. RemoteOnly enables custom error pages for remote requests, while sending detailed error messages for local requests. This attribute is required.
Child Elements
<error>
Example
The example configures a default page to be displayed to remote clients when an unhandled exception is encountered:
    <configuration>
    	<system.web>
    		<customErrors defaultRedirect="Error.aspx" />
    	</system.web>
    </configuration>
Notes
If you set the mode attribute to RemoteOnly, you will only be able to see detailed error information from the local machine on which the pages are running. Remote requests will return the custom error page (if any) configured for the status code of the error that occurred.
If you want to see the debug information provided by ASP.NET when an error occurs, the mode attribute should be set to Off.

<error> |
    <error statusCode=httpStatusCode
    	  redirect=Url />
Specifies a custom error page to handle redirections for a specific HTTP status code.
Scope
Any
Attributes statusCode Specifies the HTTP status code (such as 404 for a "Not Found" error) for the specified custom error page. This attribute is optional. redirect Specifies the URL of the page to which requests with a matching HTTP status code should be redirected. This attribute is optional.
Child Elements
None
Example
The example configures a custom error page for 404 errors, and the default error page configured in the previous example:
    <configuration>
    	<system.web>
    		<customErrors defaultRedirect="Error.aspx">
    			<error statusCode="404" redirect="My404ErrorPage.aspx"/>
    		</customErrors>
    	</system.web>
    </configuration>
Notes
While custom error pages provide a convenient way to prevent users from seeing raw error messages (and perhaps provide more helpful messages), they are not a substitute for proper exception handling. By the time an error reaches a custom error page, recovering from the error gracefully will be much more difficult, which can degrade the experience of your users.

<globalization> |
    <globalization
    		requestEncoding=encodingString
    		responseEncoding=encodingString
    		fileEncoding=encodingString
    		culture=cultureString
    		uiCulture=cultureString />
Provides attributes for configuring encoding and culture settings. These attributes are used as the basis for the expected encoding of requests, responses, and files for internationalization.
Scope
Any
Attributes requestEncoding Specifies the assumed encoding of incoming requests. This can be any valid encoding string and should match the responseEncoding attribute. The default is UTF-8. This attribute is optional. responseEncoding Specifies the content encoding of responses. This can be any valid encoding string and should match the requestEncoding attribute. The default is UTF-8. This attribute is optional. fileEncoding Specifies the encoding used to parse .aspx, .asmx, and .asax files. This attribute is optional. culture Specifies the assumed culture for incoming requests. The value can be any valid culture string. This attribute is optional. uiCulture Specifies the culture for locale-specific resource searches. The value can be any valid culture string. This attribute is optional.
Child Elements
None
Example
This example shows how the default <globalization> settings are configured in web.config:
    <configuration>
    	<system.web>
    		<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
    	</system.web>
    </configuration>
Notes
A list of valid culture strings can be found in the .NET Framework documentation for the System.Globalization.CultureInfo class.

<httpHandlers> |
    <httpHandlers>
    	<add verb=httpVerbs
    		path=pathInfo
    		type=typeInfo
    		validate=boolean />
    	<remove verb=httpVerbs
    		path=pathInfo />
    	<clear />
    </httpHandlers>
Adds or removes HttpHandlers, which are used to provide request processing for a specified HTTP verb and/or file type or path. ASP.NET itself is set up as an HttpHandler for .aspx and .asmx files, and HttpHandlers are used to prevent downloading of source code for other ASP.NET file types, such as global.asax.
Scope
Any
Attributes
None
Child Elements <add> Adds an HttpHandler. The HTTP verbs (GET, POST, etc.) handled by the HttpHandler are specified by the verb attribute; the asterisk (*) wildcard is used to specify all verbs. The path or file extension to be handled by the HttpHandler is specified by the path attribute. The class used to process the request is specified by the type attribute. This class must implement the IHttpHandler interface. Finally, the validate attribute tells ASP.NET whether or not to attempt to load the class specified by the type attribute before a matching request comes in. <remove> Removes a previously configured HttpHandler, based on the specified verb and path attributes. The attributes must match a previously configured <add> element. <clear> Clears all previously configured HttpHandlers.
Example
The example configures a custom HttpHandler for the file extension .aspnetian:
    <configuration>
    	<system.web>
    		<httpHandlers>
    			<add verb="*" path="*.aspnetian" type="aspnetian.aspnetianHandler" />
    		</httpHandlers>
    	</system.web>
    </configuration>
Notes
To make the example work properly, you need to map the file extension .aspnetian to the ASP.NET ISAPI handler, Otherwise, the request would never be handed to the custom HttpHandler. Chapter 9 has a step-by-step walkthrough of the process for mapping additional file types to the ASP.NET ISAPI handler.

<httpModules> |
    <httpModules>
    		<add name=moduleName type=typeInfo />
    		<remove name=moduleName />
    		<clear />
    </httpModules>
Adds or removes HttpModules. HttpModules are special classes that participate in the processing of all application requests. Both ASP.NET caching and session state are implemented as HttpModules, as are the authentication and authorization features of ASP.NET.

<httpRuntime> |
    <httpRuntime
       appRequestQueueLimit=numRequests
       executionTimeout=numSeconds
       maxRequestLength=numKBytes
       minFreeLocalRequestFreeThreads=numThreads
       minFreeThreads=numThreads
       useFullyQualifiedRedirectUrl=boolean />
Contains attributes used to configure the settings for the ASP.NET HTTP runtime.
Scope
Any
Attributes appRequestQueueLimit Specifies the upper limit for request queuing. Once this limit has been reached, additional requests will receive a response of "503 - Server Too Busy". The default is 100. executionTimeout Specifies the amount of time, in seconds, that a request can execute before being terminated by the runtime. The default is 90. maxRequestLength Specifies the maximum file size, in KB, that can be uploaded by a client to an ASP.NET application. This attribute is used primarily to prevent denial of launched service attacks by attempting to upload very large files to the server. The default is 4096. minFreeLocalRequestFreeThreads Specifies the minimum number of threads that will be reserved for requests from the local host that require additional threads. The default is 4. minFreeThreads Specifies the minimum number of threads that will be reserved for requests that require additional threads. The default is 8. useFullyQualifiedRedirectUrl Specifies whether URLs sent to the client for redirects are fully qualified or relative. The default is False, which specifies that the URL is relative.
Child Elements
None
Example
This example forces client-side redirect URLs to be fully qualified, which is required for some of the mobile controls supplied in the Microsoft Mobile Internet Toolkit:
    <configuration>
       <system.web>
          <httpRuntime
             useFullyQualifiedRedirectUrl="true" />
       </system.web>
    </configuration>
Notes
One of the most commonly customized attributes is maxRequestLength, since for sites that need to upload files, 4MB can be fairly limiting. Use caution when increasing this value, however; only increase it as much as necessary for the maximum file size you expect. Making this value too large can make your site vulnerable to denial-of-service attacks.

<identity> |
    <identity
       impersonate=boolean
       userName=string
       password=string />
Specifies whether request impersonation is enabled, as well as the identity to be used for requests made from the ASP.NET worker process and the password for that identity.
Scope
Any
Attributes impersonate Specifies whether impersonation is enabled for the application. If True, requests made by the ASP.NET worker process will be made with the security context of the account specified by the userName attribute; if that attribute is blank, the context of the account of the logged on user. The default is False. userName Specifies the username of the Windows account to use for impersonation. If the value is left blank or is omitted, requests will be made in the context of the logged-in user. password Specifies the password for the account named in the userName attribute. This password is stored in clear text.
Child Elements
None
Example
The example turns on impersonation for the logged-in user authenticated by IIS:
    <configuration>
       <system.web>
          <identity
             impersonate="true"
             userName="" />
       </system.web>
    </configuration>
Notes
Because the password attribute stores passwords in readable text, you should carefully consider whether it makes sense to use this functionality. Storing sensitive information such as passwords in text files presents a potential security risk.

<machineKey> |
    <machineKey
       validationKey="autogenerate|value"
       decryptionKey="autogenerate|value"
       validation="SHA1|MD5|3DES" />
Specifies the settings for cryptographic keys used for validation and decryption of Forms Authentication cookies.
Scope
All
Attributes validationKey The key used for validation of forms authentication cookie data, MAC checking of ViewState, and session state cookies. The default is autogenerate, which generates and stores a random key. For web farm implementations, you can set this value to the same 40 to 128-character key value on each server to ensure that all servers can validate successfully. decryptionKey The key used for decryption of forms authentication cookie data. The default is autogenerate, which generates and stores a random key. For web farm implementations, you can set this value to the same 40 to 128-character key value on each server to ensure that all servers can validate successfully. validation Specifies the type of encryption used for data validation.
Child Elements
None
Notes
For web farms, ensuring that the validationKey and decryptionKey values are synchronized across all servers in the farm is important. If they are not synchronized, you may get errors in Forms Authentication, ViewState errors, or problems with session state.

<pages> |
    <pages
       buffer=boolean
       enableSessionState="true|false|ReadOnly"
       enableViewState=boolean
       enableViewStateMac=boolean
       autoEventWireup=boolean
       smartNavigation=boolean
       pageBaseType=typeInfo
       userControlBaseType=typeInfo />
Contains attributes used to configure the default settings for ASP.NET pages and user controls. These settings can be overridden by attributes on the @ Page or @ Control directive.
Scope
Any
Attributes buffer Specifies whether buffering of page output is on or off. The default is True. enableSessionState Specifies whether a page has access to the Session state module. Acceptable values include True, False, and ReadOnly. The default is True. enableViewState Specifies whether ViewState is enabled at the page level. The default is True. enableViewStateMac Specifies at the page level whether a machine authentication check (MAC) is performed on the ViewState hidden field. This specification can help identify client-side tampering with the ViewState. The default is True. autoEventWireup Specifies whether ASP.NET will automatically support specific page events, such as Page_Load. The default is True. smartNavigation Specifies whether the Smart Navigation feature, for which IE 5 or above provides support for posting back and refreshing only portions of a page, is turned on at the page level. The default is False. pageBaseType Specifies the base class from which all pages are derived. The default is System.Web.UI.Page. userControlBaseType Specifies the base class from which all user controls are derived. The default is System.Web.UI.UserControl.
Child Elements
None
Example
The example disables both Session state and ViewState at the page level:
    <configuration>
       <system.web>
          <pages
             enableSessionState="false"
             enableViewState="false"/>
       </system.web>
    </configuration>
Notes
The <pages> element is very useful for setting application-level (or folder-level) defaults for pages in your application. One possible use is to place pages that do not require access to session state in a separate folder and use the <pages> element to disable session state for that folder. In this case, a session will not be created for a user until the user requests a page in your application for which EnableSessionState is True.
The default setting of EnableSessionState is True. It's important to remember this because the MAC check uses the settings in the <machineKey> element to create an encrypted version of the ViewState hidden field. In a web farm scenario, the <machineKey> settings for each server in the farm must match. Otherwise, the MAC check will fail when a user's initial request is handled by one server, while a subsequent postback is handled by another server with different settings for <machineKey>.

<processModel> |
    <processModel
       enable=boolean
       timeout="Infinite"|HH:MM:SS
       idleTimeout="Infinite"|HH:MM:SS
       shutdownTimeout="Infinite"|HH:MM:SS
       requestLimit=numRequests
       requestQueueLimit="Infinite"|numRequests
       restartQueueLimit="Infinite"|numRequests
       memoryLimit=percentMemory
       cpuMask=cpuNumBitMask
       webGarden=boolean
       userName=username
       password=password
       logLevel="All|None|Errors"
       clientConnectedCheck=HH:MM:SS
       comAuthenticationLevel="Default|None|Connect|Call|Pkt|
          PktIntegrity|PktPrivacy"
    comImpersonationLevel="Default|Anonymous|Identify|Impersonate|
       Delegate"
       responseRestartDeadlockInterval="Infinite"|HH:MM:SS
       responseDeadlockInterval="Infinite"|HH:MM:SS
       maxWorkerThreads=numThreads
       maxIoThreads=numThreads
       serverErrorMessageFile=fileName />
Contains attributes used to configure the ASP.NET worker process in IIS 5.
Scope
Machine Only
Attributes enable Specifies whether the <processModel> settings are enabled. The default is True. timeout Specifies the life span, in the format hh:mm:ss, of the process. When this value expires, a new process is started and the current process is shut down. To disable the timeout, use the value Infinite. The default is Infinite. idleTimeout Specifies the life span of the process, when idle, in the format hh:mm:ss. When this value expires, the current process is shut down. To disable the timeout, use the value Infinite. The default is Infinite. shutdownTimeout Specifies the amount of time, in the format hh:mm:ss, that the process is given to shut down gracefully. When this value expires, the process will be killed. To disable the timeout, use the value Infinite. The default is 0:00:05. requestLimit Specifies the number of requests that can be served by the ASP.NET process before it is shut down and restarted. This attribute can be used to proactively restart the ASP.NET process to compensate for memory leaks or other problems that may be associated with legacy resources (such as COM components) that you need to use in your applications. The default is Infinite, which disables this feature. requestQueueLimit Specifies the number of requests that can be queued by ASP.NET before it is shut down and restarted. This attribute can be used to proactively remedy situations in which resource contention causes requests to be queued. The default is 5000. restartQueueLimit Specifies the number of requests that will remain in the request queue while a process restart based on the requestQueueLimit setting occurs. The default is 10. memoryLimit Specifies the upper limit, as a percentage, of the server's physical memory that the ASP.NET process will be allowed to use. If this value is exceeded, a new process will be started up and the current process will be shut down. The default is 60. cpuMask Used in web garden scenarios to specify the CPU or CPUs in a multiprocessor server that will run the ASP.NET process. This value is a bitmask. The default is 0xffffffff, which specifies that a worker process should be created for every CPU. webGarden Specifies whether web gardening, in which worker processes are tied to specific processors within a multiprocessor server, is enabled. The default is False. userName Specifies the identity under which the ASP.NET worker process will be run. This can be a valid NT account or one of two special values: SYSTEM Runs the ASP.NET process as the SYSTEM account, which is a highly privileged administrative account. machine Runs the ASP.NET process as the ASPNET account (installed with the .NET Framework), which is a special account with few privileges. This process is the default and provides superior out-of-the box security for web applications written with ASP.NET. Note that the documentation for the <processModel> element incorrectly states that SYSTEM is the default. password Specifies the password of the account specified by the userName attribute. Use the value AutoGenerate (the default) when using the SYSTEM or machine accounts. logLevel Specifies the type of process events that are logged to the NT event log. Valid values are: All All process events will be logged. Errors Only errors will be logged; this is the default. None No process events will be logged. clientConnectedCheck Specifies the amount of time, in the format hh:mm:ss, that a request remains in the queue before the ASP.NET process checks to ensure that the client is still connected. The default is 0:00:05. comAuthenticationLevel Specifies the authentication level used for DCOM security. The default is Connect. comImpersonationLevel Specifies the authentication level used for COM security. The default is Impersonate. responseRestartDeadlockInterval Specifies the amount of time, in the format hh:mm:ss, that will be allowed to elapse between process restarts due to the responseDeadlockInterval attribute value. This specification prevents constant process cycling due to deadlocks. To disable this feature, use the value Infinite. The default is 0:09:00. responseDeadlockInterval Specifies the amount of time, in the format hh:mm:ss, that may elapse without a response when requests are queued. When this value expires, the process will be shut down and restarted. To disable this feature, use the value Infinite. The default is 0:03:00. maxWorkerThreads Specifies the upper limit for worker threads per CPU in the thread pool. The default is 25. maxIoThreads Specifies the upper limit for IO threads per CPU in the thread pool. The default is 25. serverErrorMessageFile Specifies the filename of a file to be displayed when a "Server Unavailable" error occurs.
Child Elements
None
Notes
In IIS 6 native mode, the settings in the <processModel> element will be ignored.
Because the settings in the <processModel> element are read by and applied to the unmanaged aspnet_isapi.dll handler that passes requests to the managed aspnet_wp.exe worker process (rather than by managed code), changes to the <processModel> element will not be applied until IIS is restarted.

<securityPolicy> |
    <securityPolicy>
       <trustLevel
          name=trustLevelName
          policyFile=fileName />
    </securityPolicy/>
Configures mappings of trust names (used by the <trust> element) to security policy files. The security policy files contain elements that configure the code access security permissions that are specific to that trust level. <securityPolicy> can contain one or more <trustLevel> elements.
Scope
Machine, Application
Attributes
None
Child Elements <trustLevel> Each <trustLevel>element maps a trust-level name to a specific policy file that implements the code access security permissions for that trust level. The name attribute specifies the name by which the trust level will be referred in the <trust> element, while the policyFile attribute specifies the name of the policy file to map to the name.
Example
This example comes from the default <securityPolicy> element in machine.config:
    <securityPolicy>
       <trustLevel
          name="Full"
          policyFile="internal" />
       <trustLevel
          name="High"
          policyFile="web_hightrust.config" />
       <trustLevel
          name="Low"
          policyFile="web_lowtrust.config" />
       <trustLevel
          name="None"
          policyFile="web_notrust.config" />
    </securityPolicy>
Notes
For a specific application, if you want to modify the code access security permissions applied, you could create a new CAS policy file and map that file to a custom trust level by using the <trustLevel> element. To implement the new security policy, you would add a <trust> element to the web.config file of the desired application and use it to specify the mapped policy file by name.

<sessionState> |
    <sessionState
       mode="Off|Inproc|StateServer|SQLServer"
       cookieless=boolean
       timeout=numMinutes
       stateNetworkTimeout=numSeconds
       stateConnectionString="tcpip=server:port"
       sqlConnectionString=connString/>
Scope
Machine, Application
Attributes mode Specifies whether session state is enabled, and if so, how the state data will be stored. Valid values are: Off The session state is disabled. InProc The session state data will be stored in memory on the local server. This is the same model as session state in classic ASP. This session state mode does not allow session state to be shared across servers in a web farm. StateServer The session state data will be stored in memory in a special NT state service on a designated state server. This session state mode allows session state to be shared across servers in a web farm. SQLServer The session state data will be stored in a special SQL Server database on a designated SQL Server. This session state mode allows session state to be shared across servers in a web farm. This mode also requires running a SQL query (which is included with the .NET Framework SDK) to set up the SQL Server database. The default is InProc. cookieless Specifies whether or not cookies will be used to associate users with specific sessions. If set to True, the session identifier will be automatically munged into the URL for each request. This requires that your application use relative URLs to work correctly. The default is False. timeout Specifies the amount of time, in minutes, before the session will time out when inactive (no requests are received with that SessionID). The default is 20. stateNetworkTimeout Specifies the amount of time, in seconds, that network operations will time out when working with the StateServer session state mode. The default is 10. stateConnectionString Specifies the server name or IP address and TCP port number for the session state server when using StateServer mode. This attribute is required when the mode attribute is StateServer. The default is tcpip=127.0.0.1:42424. sqlConnectionString Specifies the SQL Server name and authentication credentials when using SQLServer session mode. This attribute is required when the mode attribute is SQLServer. The default is data source=127.0.0.1;userid=sa;password=. Where possible, this value should use trusted connections to avoid storing a SQL userID and password in the web.config or machine.config file. To support SQL Server state mode, you need to run the InstallSqlState.sql batch file on the target SQL server to create the ASPState database and its associated tables and stored procedures. This file is installed by default in the %windir%\Microsoft.NET\Framework\%version% folder.
Child Elements
None
Example
The example configures session state to run in SQL Server mode without cookies:
    <configuration>
       <system.web>
          <sessionState
             mode="SQLServer"
             cookieless="true"
             sqlConnectionString="data source=myServer;trusted_
    connection=true" />
       </system.web>
    </configuration>
Notes
To use SQL Server mode with a trusted connection, the account identity of the ASP.NET worker process must have a login to the SQL Server database and must have permission to access the ASPState and TempDB databases. If you cannot use a trusted connection, you should create a special account specifically to access the state database, and use that account for the sqlConnectionString attribute.
Note that when using either of the out-of-process session state modes, it's wise to use the EnableSessionState attribute of the @ Page directive to disable session state for pages in your application that do not use it. Otherwise, these pages will make unnecessary cross-machine calls to retrieve unused session state information. If you have a page that reads session data but does not alter it, you can also set the EnableSessionState attribute to ReadOnly to avoid the cross-machine call to store updated session data.

<trace> |
    <trace
       enabled=boolean
       localOnly=boolean
       pageOutput=boolean
       requestLimit=numRequests
       traceMode="SortByTime|SortByCategory" />
Scope
Any
Attributes enabled Specifies whether tracing is enabled. The default is False. localOnly Specifies whether or not trace output can be viewed by machines other than the local host. The default is True. pageOutput Specifies whether trace output is rendered to the page or stored in memory and made accessible by the special Trace.axd URL. Trace.axd maps to an HttpHandler that displays all currently stored traces for a given application. The default is False. requestLimit Specifies the number of requests that can be stored in the trace buffer read by Trace.axd. Once the total number of request traces specified by this attribute has been stored, no more traces will be stored until the trace log has been cleared. The page displayed by Trace.axd includes a link for clearing the trace log. The default is 10. traceMode Specifies the sort order of items in the Trace Information section of the trace. Valid values are SortByTime and SortByCategory. SortByCategory is useful when you are using Trace.Write and Trace.Warn with your own category names passed as parameters. The default is SortByTime.
Child Elements
None
Example
This example turns tracing on at the application level:
    </configuration>
        <system.web>
            <trace enabled="true" />
       </system.web>
    </configuration>
Notes
Chapter 10 provides an overview of how to use the trace functionality of ASP.NET.

<trust> |
    <trust
       level="Full|High|Low|None"
       originUrl=URL />
Assigns a named trust level created with the <trustLevel> child element of the <securityPolicy> element to a machine, a site, or an application.
Scope
Machine, Application
Attributes level Specifies the trust level to be applied. This attribute can be any value defined by the <securityPolicy> element. The default is Full. This attribute is required. originUrl Specifies URL of origin of an application. This attribute allows classes such as WebRequest, which may need the origin host information for certain security permissions, to work properly. This attribute is optional.
Child Elements
None
Example
This example sets the application CAS permissions, based on a custom trust level:
    <configuration>
       <system.web>
          <trust level="myTrustLevel" />
       </system.web>
    </configuration>
Notes
Make sure that you understand the security implications of using custom security policy mappings before using this element. Incorrect permissions can cause major problems for your application.

<location> |
    <location
       path=pathToConfigure
       allowOverride=boolean >
       <system.web>
          <! --  Configuration settings  -- >
       </system.web>
    </location>
Allows you to prevent settings in machine.config or web.config from being overridden in child configuration files. You can also use it to configure settings for specific files or folders from a configuration file in a parent folder.
Scope
Any
Attributes path Specifies the path to the file or folder to which the configuration settings contained in the <location> tag pair should be applied. allowOverride Specifies whether child configuration files can override values configured within the <location> tag pair. This attribute locks down configuration settings (i.e., at the machine.config level) for which you want to enforce uniformity.
Child Elements
<system.web>
Example
The example, if used in machine.config, would force all applications on the machine to use Windows authentication:
    <configuration>
       <location
          allowOverride="false">
          <system.web>
             <authentication mode="Windows">
          </system.web>
       </location>
       <system.web>
          <!-- Other configuration settings -->
       </system.web>
    </configuration>
Notes
This tag provides powerful control over configuration. In addition to the scenario of enforcing an authentication method across all applications, you can also use the path attribute to configure multiple child folders or files from the web.config file in the root of the application. Using this configuration can avoid having a large number of child web.config files to manage for a larger application.