Any section in a configuration file can include content from a different file using theconfigSource attribute in thesection.. Listing 31-27: Adding additional content to the web.config f
Trang 1❑ validateRequest: Specifies whether ASP.NET should validate all the incoming requests that
are potentially dangerous like the cross-site script attack and the script injection attack This fea-ture provides out-of-the-box protection against cross-site scripting and script injection attacks by automatically checking all parameters in the request, ensuring that their content does not include HTML elements For more information about this setting, visithttp://www.asp.net/faq/
RequestValidation.aspx
❑ namespaces: Optionally, you can import a collection of assemblies that can be included in the
precompilation process
❑ compilationMode: Specifies how ASP.NET should compile the current Web application
Sup-ported values areNever,Always, andAuto When you setcompilationMode = "Never", this
means that the pages should never be compiled A part error occurs if the page has constructs
that require compilation When you setcompilationMode = "Always", this means that the pages are always compiled When you setcompilationMode = "Auto", ASP.NET does not compile the pages if that is possible
Include Files
Unlike ASP.NET 1.0 and 1.1, ASP.NET 2.0 and 3.5 support include files in both themachine.config
and theweb.configfiles When configuration content is to be included in multiple places or inside the
location elements, an include file is an excellent way to encapsulate the content
Any section in a configuration file can include content from a different file using theconfigSource
attribute in the<pages>section The value of the attribute indicates a virtual relative filename to the
include file Listing 31-27 is an example of such a directive
Listing 31-27: Adding additional content to the web.config file
<configuration>
<system.web>
<pages configSource="SystemWeb.config" />
</system.web>
</configuration>
The configuration include files can contain information that applies to a single section, and a single
include file cannot contain more than one configuration section or a portion of a section If the config-Sourceattribute is present, the section element in the source file should not contain any other attribute
or any child element
Nevertheless, the include file is not a full configuration file It should contain only the include section, as presented in Listing 31-28
Listing 31-28: The SystemWeb.config file
<pages authentication mode="Forms" />
TheconfigSourceattribute cannot be nested An include file cannot nest another file inside it using the configSourceattribute
When an ASP.NET configuration file is changed, the application is restarted at runtime When an
exter-nal include file is used within the configuration file, the configuration reload happens without restarting
the application.
Trang 2Configuring ASP.NET Runtime Settings
The general configuration settings are those that specify how long a given ASP.NET resource, such as a
page, is allowed to execute before being considered timed-out The other settings specify the maximum
size of a request (in kilobytes) or whether to use fully qualified URLs in redirects These settings can be
specified using the<httpRuntime>section within a configuration file The<httpRuntime>element is
applied at the ASP.NET application at the folder level Listing 31-29 shows the default values used in the
<httpRuntime>section
Listing 31-29: The<httpRuntime> section
<configuration>
<system.web>
<httpRuntime
useFullyQualifiedRedirectUrl="false"
enable="true"
executionTimeout="90"
maxRequestLength="4096"
requestLengthDiskThreshold="512"
appRequestQueueLimit="5000"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
enableKernelOutputCache="true" />
</system.web>
</configuration>
Enabling and Disabling ASP.NET Applications
Theenableattribute specifies whether the current ASP.NET application is enabled When set tofalse,
the current ASP.NET application is disabled, and all the clients trying to connect to this site receive the
HTTP 404 — File Not Found exception This value should be set only at the machine or application level
If you set this value in any other level (such as subfolder level), it is ignored This great feature enables
the administrators to bring down the application for whatever reason without starting or stopping IIS
The default value istrue
Outside of this setting, it is also possible to take applications offline quickly by simply placing an
App_Offline.htmfile in the root of your application This.htmfile does not need to actually contain
anything (it will not make any difference) Just having the file in the root directory causes the application
domain to come down, and all requests to the application get a Page Not Found error.
Fully Qualified Redirect URLs
TheuseFullyQualifiedRedirectUrlattribute specifies whether the client-side redirects should include
the fully qualified URL When you are programming against the mobile devices, some devices require
specifying fully qualified URLs The default value isfalse
Request Time-Out
TheexecutionTimeoutsetting specifies the timeout option for an ASP.NET request time-out The value
of this attribute is the amount of time in seconds during which a resource can execute before ASP.NET
Trang 3times the request out The default setting is 110 seconds If you have a particular ASP.NET page or Web service that takes longer than 110 seconds to execute, you can extend the time limit in the configuration Maximum Request Length
ThemaxRequestLengthattribute specifies the maximum file-size upload accepted by ASP.NET runtime For example, if the ASP.NET application is required to process huge files, it is better to change this setting The default is 4096 This number represents kilobytes (KB or around 4 MB)
Web applications are prone to attacks these days The attacks range from a script injection attack to a
denial of service (DoS) attack The DoS is a typical attack that bombards the Web server with requests for large files This huge number of requests ultimately brings down the Web server ThemaxRequestLength attribute could save you from a DoS attack by setting a restriction on the size of requests
Buffer Uploads
In ASP.NET 1.0 or 1.1, when a HTTP post is made (either a normal ASP.NET form post, file upload,
or an XMLHTTP client-side post), the entire content is buffered in memory This works out fine for
smaller posts However, when memory-based recycling is enabled, a large post can cause the ASP.NET worker process to recycle before the upload is completed To avoid the unnecessary worker process
recycling, ASP.NET 3.5 includes a setting calledrequestLengthDiskThreshold This setting enables an administrator to configure the file upload buffering behavior without affecting the programming model Administrators can configure a threshold below which requests will be buffered into memory After a
request exceeds the limit, it is transparently buffered on disk and consumed from there by whatever
mechanism is used to consume the data The valid values for this setting are numbers between1and
Int32.MaxSizein KB
When file buffering is enabled, the files are uploaded to thecodegenfolder The default path for the
codegenfolder is the following:
[WinNT\Windows]\Microsoft.NET\Framework\[version]\Temporary ASP.NET Files\
[ApplicationName]
The files are buffered using a random name in a subfolder within thecodegenfolder calledUploads
The location of thecodegenfolder can be configured on a per application basis using thetempDirectory attribute of the<compilation>section
This is not a change in ASP.NET; rather it is an internal change When an ASP.NET 1.0 or 1.1
appli-cation is migrated to the NET Framework 2.0 or 3.5, the ASP.NET appliappli-cation automatically takes
advantage of this feature.
Thread Management
ASP.NET runtime uses free threads available in its thread pool to fulfill requests TheminFreeThreads
attribute indicates the number of threads that ASP.NET guarantees is available within the thread pool
The default number of threads is eight For complex applications that require additional threads to com-plete processing, this simply ensures that the threads are available and that the application will not
be blocked while waiting for a free thread to schedule more work TheminLocalRequestFreeThreads
attribute controls the number of free threads dedicated for local request processing; the default is four
Trang 4Application Queue Length
TheappRequestQueueLimitattribute specifies the maximum number of requests that ASP.NET queues
for the current ASP.NET application ASP.NET queues requests when it does not have enough free
threads to process them TheminFreeThreadsattribute specifies the number of free threads the ASP.NET
application should maintain, and this setting affects the number of items stored in the queue
When the number of requests queued exceeds the limit set in theappRequestQueueLimitsetting, all the
incoming requests are rejected and anHTTP 503 - Server Too Busyerror is thrown back to the browser.
Output Caching
TheenableKernelOutputCachespecifies whether the output caching is enabled at the IIS kernel level
(Http.sys) At present, this setting applies only to Web servers IIS6 and higher
Configuring the ASP.NET Worker Process
When a request for an ASP.NET page is received by IIS, it passes the request to an unmanaged DLL called
aspnet_isapi.dll Theaspnet_isapi.dllfurther passes the request to a separate worker process,
aspnet_wp.exeif you are working with IIS5, which runs all the ASP.NET applications With IIS6 and
higher, however, all the ASP.NET applications are run by thew3wp.exeprocess The ASP.NET worker
process can be configured using the<processModel>section in themachine.configfile
All the configuration sections talked about so far are read by managed code On the other hand, the
<processModel> section is read by theaspnet_isapi.dllunmanaged DLL Because the
configura-tion informaconfigura-tion is read by an unmanaged DLL, the changed process model informaconfigura-tion is applied to all
ASP.NET applications only after an IIS restart.
The code example in Listing 31-30 shows the default format for the<processModel>section
Listing 31-30: The structure of the<processModel> element
<processModel
enable="true|false"
timeout="hrs:mins:secs|Infinite"
idleTimeout="hrs:mins:secs|Infinite"
shutdownTimeout="hrs:mins:secs|Infinite"
requestLimit="num|Infinite"
requestQueueLimit="num|Infinite"
restartQueueLimit="num|Infinite"
memoryLimit="percent"
cpuMask="num"
webGarden="true|false"
userName="username"
password="password"
logLevel="All|None|Errors"
clientConnectedCheck="hrs:mins:secs|Infinite"
responseDeadlockInterval="hrs:mins:secs|Infinite"
responseRestartDeadlockInterval="hrs:mins:secs|Infinite"
comAuthenticationLevel="Default|None|Connect|Call|
Trang 5comImpersonationLevel="Default|Anonymous|Identify|
Impersonate|Delegate"
maxWorkerThreads="num"
maxIoThreads="num"
/>
The following section looks at each of these attributes in more detail:
❑ enable: Specifies whether the process model is enabled When set tofalse, the ASP.NET appli-cations run under IIS’s process model
When ASP.NET is running under IIS6 or higher in native mode, the IIS6 or higher process
model is used and most of the <processModel> section within the configuration file is simply
ignored TheautoConfigandrequestQueueLimitattributes are still applied in this case.
❑ timeout: Specifies how long the worker process lives before a new worker process is created to
replace the current worker process This value can be extremely useful if a scenario exists where the application’s performance starts to degrade slightly after running for several weeks, as in the case of a memory leak Rather than your having to manually start and stop the process, ASP.NET can restart automatically The default value isInfinite
❑ idleTimeout: Specifies how long the worker process should wait before it is shut down You
can shut down the ASP.NET worker process automatically using theidleTimeoutoption The
default value isInfinite You can also set this value to a time using the format, HH:MM:SS:
❑ shutdownTimeout: Specifies how long the worker process is given to shut itself down gracefully before ASP.NET calls theKillcommand on the process.Killis a low-level command that force-fully removes the process The default value is 5 seconds
❑ requestLimit: Specifies when the ASP.NET worker process should be recycled after a certain
number of requests are served The default value isInfinite
❑ requestQueueLimit: Instructs ASP.NET to recycle the worker process if the limit for queued
requests is exceeded The default setting is 5000
❑ memoryLimit: Specifies how much physical memory the worker process is allowed to consume
before it is considered to be misbehaving or leaking memory The default value is 60 percent of available physical memory
❑ usernameandpassword: By default, all ASP.NET applications are executed using the ASPNET
identity If you want an ASP.NET application to run with a different account, you can provide
the username and the password pair using these attributes
❑ logLevel: Specifies how the ASP.NET worker process logs events The default setting is to log
errors only However, you can also disable logging by specifyingNoneor you can log everything usingAll All the log items are written to the Windows Application Event Log
❑ clientConnectedCheck: TheclientConnectedChecksetting enables you to check whether the
client is still connected at timed intervals before performing work The default setting is
5 seconds
❑ responseDeadlockInterval: Specifies how frequently the deadlock check should occur A dead-lock is considered to exist when requests are queued and no responses have been sent during
this interval After a deadlock, the process is restarted The default value is 3 minutes
Trang 6❑ responseRestartDeadlockInterval: Specifies, when a deadlock is detected by the runtime, how
long the runtime should wait before restarting the process The default value is 9 minutes
❑ comAuthenticationLevel: Controls the level of authentication for DCOM security The default
is set toConnect Other values areDefault,None,Call,Pkt,PktIntegrity, andPktPrivacy
❑ comImpersonationLevel: Controls the authentication level for COM security The default is set
toImpersonate Other values areDefault,Anonymous,Identify, andDelegate
❑ webGarden: Specifies whether Web Garden mode is enabled The default setting isfalse A Web
Garden lets you host multiple ASP.NET worker processes on a single server, thus providing
the application with better hardware scalability Web Garden mode is supported only on
multi-processor servers
❑ cpuMask: Specifies which processors should be affinities to ASP.NET worker processes when
webGarden = "true" ThecpuMaskis a hexadecimal value The default value is all processors,
shown as 0xFFFFFFFF
❑ maxWorkerThreads: Specifies the maximum number of threads that exist within the ASP.NET
worker process thread pool The default is 20
❑ maxIoThreads: Specifies the maximum number of I/O threads that exist within the ASP.NET
worker process The default is 20
Running Multiple Web Sites with Multiple Versions of Framework
In the same context, multiple Web sites within the given Web server can host multiple Web sites, and
each of these sites can be bound to a particular version of a NET Framework This is typically done
using theaspnet_regiis.exeutility Theaspnet_regiis.exeutility is shipped with each version of the
framework
This utility has multiple switches Using the-sswitch allows you to install the current version of the
.NET Framework runtime on a given Web site Listing 31-31 shows how to install NET Framework
version 1.1 on the ExampleApplication Web site
Listing 31-31: Installing NET Framework version 1.1 on the ExampleApplication
Web site
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322>
aspnet_regiis -s W3SVC/1ROOT/ExampleApplication
Storing Application-Specific Settings
Every Web application must store some application-specific information for its runtime use The
<appSettings>section of theweb.configfile provides a way to define custom application settings
for an ASP.NET application The section can have multiple<add>subelements Its syntax is as follows:
<appSettings>
<add key="[key]" value="[value]"/>
</appSettings>
The<add>subelement supports two attributes:
❑ key: Specifies the key value in anappSettingshash table
Trang 7Listing 31-32 shows how to store an application-specific connection string Thekeyvalue is set to Appli-cationInstanceID, and thevalueis set to the ASP.NET application instance and the name of the server
on which the application is running
Listing 31-32: Application instance information
<appSettings>
<add key="ApplicationInstanceID" value="Instance1onServerOprta"/>
</appSettings>
Programming Configuration Files
In ASP.NET 1.0 and 1.1 versions of the Framework provided APIs that enabled you only to read informa-tion from the configurainforma-tion file You had no way to write informainforma-tion into the configurainforma-tion file because
no out-of-the-box support was available However, some advanced developers wrote their own APIs to write the information back to the configuration files Because theweb.configfile is an XML file, devel-opers were able to open configuration file using theXmlDocumentobject, modify the settings, and write
it back to the disk Even though this approach worked fine, the way to access the configuration settings were not strongly typed Therefore, validating the values was always a challenge
However, ASP.NET 3.5 includes APIs (ASP.NET Management Objects) to manipulate the configuration information settings inmachine.configandweb.configfiles ASP.NET Management Objects provide a strongly typed programming model that addresses targeted administrative aspects of a NET Web Appli-cation Server They also govern the creation and maintenance of the ASP.NET Web configuration Using the ASP.NET Management Objects, you can manipulate the configuration information stored in the con-figuration files in the local or remote computer These can be used to script any common administrative tasks or the writing of installation scripts
All of the ASP.NET Management Objects are stored in theSystem.ConfigurationandSystem.Web
Configurationnamespaces You can access the configuration using theWebConfigurationManager
class TheSystem.Configuration.Configurationclass represents a merged view of the configuration
settings from themachine.configand hierarchicalweb.configfiles TheSystem.Configurationand
System.Web.Configurationnamespaces have multiple classes that enable you to access pretty much
all the settings available in the configuration file The main difference betweenSystem.Configuration
andSystem.Web.Configurationnamespaces is that theSystem.Configurationnamespace contains all the classes that apply to all the NET applications On the other hand, theSystem.Web.Configuration
namespace contains the classes that are applicable only to ASP.NET Web applications The following
table shows the important classes inSystem.Configurationand their uses
Class Name Purpose
local computer or a remote one
ConfigurationElementCollection Enables you to enumerate the child elements stored inside
the configuration file
AppSettingsSection Enables you to manipulate the<appSettings>section of
the configuration file
ConnectionStringsSettings Enables you to manipulate the<connectionStrings>
section of the configuration file
Trang 8Class Name Purpose
ProtectedConfigurationSection Enables you to manipulate the<protectedConfiguration>
section of the configuration file
ProtectedDataSection Enables you to manipulate the<protectedData>section of
the configuration file
The next table shows classes from theSystem.Web.Configurationand their uses
AuthenticationSection Enables you to manipulate the<authentication>
section of the configuration file
AuthorizationSection Enables you to manipulate the<authorization>
section of the configuration file
CompilationSection Enables you to manipulate the<compilation>section
of the configuration file
CustomErrorsSection Enables you to manipulate the<customErrors>section
of the configuration file
FormsAuthenticationConfiguration Enables you to manipulate the<forms>section of the
configuration file
GlobalizationSection Enables you to manipulate the<globalization>
section of the configuration file
HttpHandlersSection Enables you to manipulate the<httpHandlers>section
of the configuration file
HttpModulesSection Enables you to manipulate the<httpModules>section
of the configuration file
HttpRuntimeSection Enables you to manipulate the<httpRuntime>section
of the configuration file
MachineKeySection Enables you to manipulate the<machineKey>section of
the configuration file
MembershipSection Enables you to manipulate the<membership>section of
the configuration file
configuration file
ProcessModelSection Enables you to manipulate the<processModel>section
of the configuration file
the configuration file
Trang 9All the configuration classes are implemented based on simple object-oriented based architecture that has
an entity class that holds all the data and a collection class that has methods to add, remove, enumerate, and so on Start your configuration file programming with a simple connection string enumeration, as
shown in the following section
Enumerating Connection Strings
In a Web application, you can store multiple connection strings Some of them are used by the system and the others may be application-specific You can write a very simple ASP.NET application that enumerates all the connection strings stored in theweb.configfile, as shown in Listing 31-33
Listing 31-33: The web.config file
<?xml version="1.0" ?>
<configuration>
<appSettings>
<add key="symbolServer" value="192.168.1.1" />
</appSettings>
<connectionStrings>
<add name="ExampleApplication"
connectionString="server=ExampleApplicationServer;
database=ExampleApplicationDB;uid=WebUser;pwd=P@$$worD9"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
<system.web>
<compilation debug="false" />
<authentication mode="None" />
</system.web>
</configuration>
As shown in Listing 31-33, one application setting points to the symbol server, and one connection string
is stored in theweb.configfile Use theConnectionStringscollection of theSystem.Web.Configuration WebConfigurationManagerclass to read the connection strings, as seen in Listing 31-34
Listing 31-34: Enum.aspx
VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
GridView1.DataSource = _
System.Web.Configuration.WebConfigurationManager.ConnectionStrings GridView1.DataBind()
End Sub
C#
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource =
System.Web.Configuration.WebConfigurationManager.ConnectionStrings;
GridView1.DataBind();
}
Trang 10As shown in Listing 31-34, you’ve bound theConnectionStringsproperty collection of the
WebConfigu-rationManagerclass into the GridView control TheWebConfigurationManagerclass returns an instance
of theConfigurationclass and theConnectionStringsproperty is a static (shared in Visual Basic)
prop-erty Therefore, you are just binding the property collection into the GridView control Figure 31-5 shows
the list of connection strings stored in the ASP.NET application
Figure 31-5
Adding a connection string at runtime is also a very easy task If you do it as shown in Listing 31-35, you
get an instance of the configuration object Then you create a newconnectionStringSettingsclass You
add the new class to the collection and call the update method Listing 31-35 shows examples of this in
both VB and C#
Listing 31-35: Adding a connection string
VB
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
’ Get the file path for the current web request
Dim webPath As String = Request.ApplicationPath
Try
’ Get configuration object of the current web request Dim config As Configuration = _
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(webPath)
’ Create new connection setting from text boxes Dim newConnSetting As New _
ConnectionStringSettings(txtName.Text, txtValue.Text, txtProvider.Text)
’ Add the connection string to the collection