Professional ASP.NET 1.1 [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Professional ASP.NET 1.1 [Electronic resources] - نسخه متنی

Alex Homeret

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید






Common Configuration Settings

If you have examined

machine.config , which I would suggest you do, you will find around 30 configuration settings. Here are the most commonly used configuration entries:



General configuration settings:How long a given ASP.NET resource, such as a page, is allowed to execute before being considered timed-out.



Page configuration:ASP.NET pages have configuration options such as whether buffering or viewstate is enabled.



Application settings:A key/value combination that allows you to store data within the configuration system and access it within your application.



Session state:Options for

Session state, such as where data is stored, timeout, and support for cookieless state management.



Tracing:Provides a trace of what the application is doing. This is configurable both at the page- level and application-level.



Custom errors:ASP.NET has several options for handling application errors, as well as common HTTP errors (404 file not found, and so on).



Security:Although we will cover security in Chapter 14, we will discuss some of the basic security configuration options.



Web services:The web services section allows you to configure some the options for ASP.NET web services such as the name and location of the

DefaultWSDLHelpGenerator.aspx template used to generate an HTML view of the web service.



Globalization:Application-level options for the request/response character encoding for ASP.NET to use.



Compilation:The compilation options allow you to control some of the compilation behaviors of ASP.NET, such as changing the default language from Visual Basic .NET to C#.



Identity:ASP.NET allows you to impersonate the user that ASP.NET acts on the behalf of.



HTTP handlers:HTTP handlers are responsible for servicing requests for a particular extension in ASP.NET such as

.aspx or

.asmx . Custom handlers can be added or existing handlers removed within this section.



HTTP modules:HTTP modules are responsible for filtering each request/response in an ASP.NET application, such as determining whether a particular request should be served from the cache or directed to an HTTP handler.



Process model:By default, ASP.NET runs out-of-process from IIS, and has the capability to recycle by itself. The settings found in this section allow granular control over the behavior of the worker process. We will also discuss the ASP.NET Worker process in this section.



Machine key:A key used for encryption or hashing of some values such as the data in the cookie used for forms authentication. In a server farm environment, all the servers must share a common machine key.




General Configuration Settings


We use the

<httpRuntime> configuration settings for general application configuration settings such as how long a request is processed before being considered timed-out, the maximum size of a request, or whether to use fully qualified URLs in redirects (a requirement for some mobile applications):

<configuration>
<system.web>

<httpRuntime

executionTimeout="90"

maxRequestLength="4096"

useFullyQualifiedRedirectUrl="false"

minFreeThreads="8"

minLocalRequestFreeThreads="4"

appRequestQueueLimit="100"

enableVersionHeader="true"

/>
</system.web>
</configuration>


There are seven configurable options:



executionTimeout .



maxRequestLength .



useFullyQualifiedRedirectUrl .



minFreeThreads .



minLocalRequestFreeThreads .



appRequestQueueLimit .



enableVersionHeader (ASP.NET 1.1 only).



Application Timeout


The

executionTimeout setting is similar to the timeout option for ASP. The value of this attribute is the amount of time in seconds for which a resource can execute before ASP.NET times the request out. The default setting is 90 seconds.

If a particular ASP.NET page or web service takes longer than 90 seconds to execute, you can extend the time limit in the configuration. A good example here is an application that makes a particularly long database request, such as generating a sales report for an application in a company's intranet. If we know the report takes 120 seconds (on average) to execute, we could set the

timeout="300" and ASP.NET would not timeout the request prematurely. Similarly, you can set the value to less than 90 seconds, and this will decrease the time ASP.NET is allowed to process the request before timing out.

Controlling the Maximum Request Length


The maximum request length attribute,

maxRequestLength , identifies the maximum size in KB of the request. By default, the maximum request length is 4 MB.

For example, if your site allows customers to upload files and you expect that content to be larger than 4 MB, you can increase this setting. Good examples here include MP3s, unusually large images such as an X-ray stored as a large uncompressed TIFF for a medical site, and so on.

Controlling the maximum request length is important, since common denial of service attacks involve spamming a web site with unusually large requests.

Fully Qualified URLs for Redirects


Some devices, such as mobile phones, that may use ASP.NET applications require that a redirect URL be fully qualified. The default behavior is for ASP.NET to send an unqualified URL for client redirects, (

/Wrox/Logon.aspx , for example). Setting

useFullyQualifiedRedirectUrl to

"true" will cause the server to send a redirect as

http://[server name]/Wrox/Logon.aspx .

Thread Management


Two of the more advanced attributes,

minFreeThreads and

minLocalRequestFreeThreads , allow you to control how ASP.NET manages threads.

The

minFreeThreads attribute indicates the number of threads that ASP.NET guarantees is available within the thread pool, the default value for which is 8. For complex applications that require additional threads to complete processing, this simply ensures that the threads are available and that the application does not need to be blocked waiting for a free thread to schedule more work.

The

minLocalRequestFreeThreads controls the number of free threads dedicated for local request processing, the default of which is 4.

Managing the Request Queue Limit


The final attribute,

appRequestQueueLimit , controls the number of client requests that may be queued, or in other words, waiting to be processed. Queuing occurs when the server is receiving requests faster than they can be processed. When the number of requests in the queue reaches this threshold, the server will begin sending a HTTP status code 503 indicating that the server is too busy to handle any more requests. If this occurs, you should consider adding another server to handle the load, or isolate and improve the performance of poorly performing ASP.NET pages or web services. A good way to do this is to take advantage of the caching features.

The 'Powered by ASP.NET' Header


New to ASP.NET 1.1 is the

<httpRuntime> enableVersionHeader flag. This attribute controls whether the ASP.NET reports the version number used on the server. By default, this value is set to true, and when requests are made to a web server using ASP.NET, the server will return several headers:

HTTP/1.1 302 Found

Content-Length: 40959

Date: Thu, 02 Oct 2003 14:45:49 GMT

Location: http://www.asp.net/default.aspx?tabindex=0&tabid=1

Content-Type: text/html; charset=utf-8

Server: Microsoft-IIS/6.0

X-Powered-By: ASP.NET

X-AspNet-Version: 1.1.4322

Cache-Control: private

As you can see, two headers X-Powered-By and X-AspNet-Version, are specific to ASP.NET. If

enableVersionHeader is set to

false , the X-AspNet-Version header is simply not returned.

In addition to configuring the application, there are also settings particular to ASP.NET pages.


Page Configuration


The page configuration settings allow you to control some of the default behaviors for all ASP.NET pages. These behaviors include options such as whether the output should be buffered before sending, and whether

Session state is enabled for pages within the application.

The following

web.config file mirrors the default settings from

machine.config :

<configuration>
<system.web>

<pages buffer="true"

enableSessionState="true"

enableViewState="true"

enableViewStateMac="false"

autoEventWireup="true"

smartNavigation="false"

pageBaseType="System.Web.UI.Page"

userControlBaseType="System.Web.UI.UserControl"

validateRequest="true"

/>
</system.web>
</configuration>


Here is what these settings allow you to control:



buffer :Whether the response to a request is buffered on the server before being sent. If

buffer="false" , the response to a request is sent as the response is available. In some cases, buffering can be disabled and the end-user will perceive that the application is responding faster. In general, however, buffering should not be disabled and the default setting of

true need not be changed.



enableSessionState :By default,

Session state is enabled for ASP.NET pages. However, if

Session is not going to be used for the application, you should disable

Session state. Disabling

Session state will conserve resources used by the application.





Note

In addition to

true and

false settings for this attribute, you can also set

enableSessionState to

readonly . We will cover the

readonly option later in the chapter when we discuss the

<sessionState> settings.




enableViewState :By default, viewstate, a means of storing server control data on the client, is round-tripped within a hidden form element (

__VIEWSTATE ) in ASP.NET pages. If the application will not use viewstate, you can set the value to

false in the application's

web.config file.



autoEventWireup :ASP.NET can automatically wire up common page events such as

Load or

Error , allowing you to simply author an event prototype such as

Page_Load . Setting

autoEventWireup to

"false" , the default behavior of Visual Studio .NET, forces us (done automatically with Visual Studio .NET) to override the appropriate Page events.



smartNavigation :Smart navigation is a feature that takes advantage of a client's browser (Internet Explorer only) to prevent the flickering/redrawing seen when a page is posted back to itself. Instead, using smart navigation, the request is sent through an IFRAME on the client and IE only redraws the sections of the page that have changed. By default, this is set to

false , and when enabled, is only available to Internet Explorer browsers – all other browsers will get the standard behavior.



pageBaseType :An advanced option, this attribute controls the base class that all ASP.NET Pages inherit from. By default, it is set to

System.Web.UI.Page . However, if you wish all of your pages to inherit from some other base class – for example

ACME.Web.Page – you could configure this option here.



userControlBaseType :An advanced option similar to

pageBaseType , this attribute allows you to control the base class that all user controls inherit from. The default is

System.Web.UI.UserControl .



validateRequest (ASP.NET 1.1):When

validateRequest is set to

true , content that is posted back to the server is checks for unencoded HTML. If unencoded HTML is found, an exception is thrown that prevents that data from being posted to the application. This is designed to prevent sites from allowing cross-site scripting attacks by posting content into the application. For more on this feature visit http://www.asp.net/faq/RequestValidation.aspx.





Note

Note that all of the preceding settings can be overridden within a given ASP.NET page. For example, you can disable view state at the control-level on individual pages. See Chapter 5 for more details.




Application Settings


The application settings section,

<appSettings/> , allows you to store application configuration details within the configuration file without needing to write your own configuration section handler. The use of these key/value pair settings simply populates a hashtable that you can access within your application. The following simple example stores the DSN for a connection to a database and a SQL statement:

<configuration>
<appSettings>

<add key="DSN"

value="server=sql1;uid=cust;pwd=8d$net;database=pubs" />

<add key="SQL_PRODUCTS"

value="SELECT Name, Price FROM Products" />
</appSettings>
</configuration>


You can then retrieve these settings within your ASP.NET application:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
Private dsn As String
Private sql As String
Public Sub Page_Load()

dsn = ConfigurationSettings.AppSettings("DSN")

sql = ConfigurationSettings.AppSettings("SQL_PRODUCTS")
Dim myConnection As New SqlConnection(dsn)
Dim myCommand As New SqlCommand(sql, myConnection)
Dim reader As DataReader
myConnection.Open()
If (reader.Read) Then
datagrid1.DataSource = reader
datagrid1.DataBind()
End If
myConnection.Close()
End Sub
</script>
<asp:DataGrid id=datagrid1 runat="server" />


Storing this type of commonly used information within the configuration system allows you to manage common application details in a single location, and if the configuration data changes – such as changing the password value of the DSN or the columns in the

select statement – the application is automatically restarted and the new values used.

Session State


Session state is dedicated data storage for each user within an ASP.NET application. It is implemented as a

Hashtable and stores data, based on key/value pair combinations (for details on how to use the

Session programmatically, see the previous chapter).

Classic ASP

Session state has two main shortcomings:



Web farm challenges:

Session data is stored in memory on the server it is created upon. In a web farm scenario, where there are multiple web servers, a problem could arise if a user was redirected to a server other than the server upon which they stored their

Session state. Normally this can be managed by an IP routing solution where the IP address of the client is used to route that client to a particular server – in other words 'sticky sessions'. However, some ISPs use farms of reverse proxies, and so the client request may come through a different IP on each request. When a user is redirected to a server other than the server that contains their

Session data, poorly designed applications can break.



Supporting clients that do not accept HTTP cookies:The Web is inherently a stateless environment. To use

Session state, the client and web server need to share a key that the client can present to identify its

Session data on subsequent requests. Classic ASP shared this key with the client through the use of an HTTP cookie. While this scenario worked well for clients that accept HTTP cookies, it broke the small minority of users that rejected HTTP cookies.



Both of these issues are addressed in ASP.NET

Session , which supports new features to remedy these problems:



Web farm support:ASP.NET

Session supports storing the

Session data either in-process (in the same memory that ASP.NET uses), out-of-process using Windows NT Service (in separate memory from ASP.NET), or in SQL Server (persistent storage). Both the Windows Service and SQL Server solutions support a web farm scenario where all the web servers can be configured to share a common

Session store. Thus, as users get routed to different servers, each server is able to access that user's

Session data. To the developer programming with

Session , this is completely transparent and does not require any changes in the application code. Rather, we simply configure ASP.NET to support one of these out-of-process options.



Cookieless mode:Although supported to an extent in ASP through the use of an ISAPI filter (available as part of the IIS 4.0 SDK), ASP.NET makes cookieless support for

Session a first class feature. However, by default

Session still uses HTTP cookies. When cookieless mode is enabled, ASP.NET will embed the session ID (normally stored in the cookie), into the URL that is sent back to the client. When the client makes a request using the URL containing the

Session ID, ASP.NET is able to extract the

Session ID and map the request to the appropriate

Session data.



Let's take a look at the configuration settings used to enable these options.

Configuration Settings


The

sessionState configuration settings within

web.config or

machine.config allow you to configure how you take advantage of the

Session features previously described. The following sample

web.config file mirrors the defaults found in

machine.config :

<configuration>
<system.web>

<sessionState

mode="InProc"

stateConnectionString="tcpip=127.0.0.1:42424"

stateNetworkTimeout="10"

sqlConnectionString="data source=127.0.0.1; user id=sa;password="

cookieless="false"

timeout="20"

lockAttributes="sqlConnectionString, stateConnectionString"

/>
</system.web>
</configuration>


The

<sessionState> configuration setting supports the following attributes (we will show their use shortly):



mode :The

mode setting supports four options:

Off ,

InProc ,

SQLServer , and

StateServer . The

InProc option, the default, enables in-process state management. In-process state management is identical to the behavior of ASP

Session . There are also two options for out-of- process state management: a Windows NT Service (

StateServer ) and SQL Server (

SQLServer ).



stateConnectionString :Identifies the TCP/IP address and port used to communicate with the Windows NT Service providing state management facilities. You must configure the

stateConnectionString when

mode is set to

StateServer .



stateNetworkTimeout :Controls the timeout, in seconds, allowed when attempting to store state in an out-of-process session store.



sqlConnectionString :Identifies the database connection string that names the database used for

mode="SQLServer" . This includes both the TCP/IP address identified by

data source as well as a username and password to connect to the SQL Server database.



cookieless :Enables support for

Session key management without requiring HTTP cookies.



timeout :This option controls the life of a user's

Session .

timeout is a sliding value, and on each request the timeout period is reset to the current time plus the timeout value.



lockAttributes (ASP.NET 1.1):This option allows the server owner the lock the attribute values an not allow these values to be overridden in child applications. For example, locking the out-of-process SQL Server connection string would force all users to use the same SQL Server database as opposed to allowing them to specify their own. This is not enabled by default.



Next, let's implement some of the common scenarios encountered when building applications using

Session state.

Supporting Web Farms


By default, ASP.NET ships with

Session state configured to store

Session data in the same process as ASP.NET. This is identical to how ASP

Session data is stored. The session web farm feature allows several front-end web servers to share a common storage point for

Session data, rather than each web server maintaining its own copy. This creates a scenario in which the client making the request can be serviced from any server within the server farm. Additionally this allows an individual server's process to recycle and access to

Session data to be maintained.

There are two options for out-of-process

Session state: a Windows NT Service that stores the data (in memory) in a separate process from ASP.NET (either on the same server or on a different server), and a SQL Server option that stores the data in SQL Server. Let's look at how to configure both of these options.

Out-Of-Process – Windows NT Service

To support the out-of-process Windows Service option (

mode="StateServer" ), you first need to decide which server is going to run the Windows Service used for

Session state storage. ASP.NET ships with a Windows Service named

aspnet_state that needs to be running so that

Session functions in

mode="StateServer" .

The service can be started by opening a command prompt and entering the following:


> net start aspnet_state
The ASP.NET State Service service is starting.
The ASP.NET State Service service was started successfully.

Alternatively, you can configure the service using the Services and Applications Microsoft Management Console MMC snap-in (available from Start | Settings | Control Panel | Administrative Tools | Computer Management). If you view the Services item in this tool, you are presented with a list of the available services on the server as shown in Figure 13-3:


Figure 13-3:

Right-clicking on the ASP.NET State Service item opens up a menu that allows you to configure how this service is to be run. You can select the start-up options (whether Windows should automatically start this service for you) as well as use the toolbar Start and Stop buttons to enable or disable this service.

Once the service has been started, ASP.NET must be configured to use this particular service. This is done through your configuration file. You need to tell ASP.NET which server and port to use for communication with the ASP.NET State service, as well as the fact that the Windows Service state option is to be used.

Here is the

web.config , with the necessary settings highlighted:

<configuration>
<system.web>
<sessionState

mode="StateServer"

stateConnectionString="tcpip=127.0.0.1:42424"
stateNetworkTimeout="10"
sqlConnectionString="data source=127.0.0.1; user id=sa;password="
cookieless="false"
timeout="20"
/>
</system.web>
</configuration>


In this example, ASP.NET

Session is directed to use the Windows Service for state management on the local server (the address 127.0.0.1 is the TCP/IP loop-back address).

The default port that

aspnet_state uses to communicate is 42424; you can configure this to any other port you wish, but this configuration must be done through the system registry. To configure the port to 100, run

RegEdit.exe and expand HKEY_LOCAL_MACHINE | SYSTEM | CurrentControlSet | Services | aspnet_state | Parameters. Within Parameters, you will find a Port setting, which allows you to configure the TCP/IP port which the

aspnet_state service uses to communicate as shown in Figure 13-4:


Figure 13-4:





Note

In ASP.NET version 1.1, due to security reasons, only local machines can connect to the state server. To allow only non-local host requests in ASP.NET 1.1, open the same registry entry for the port setting

HKLM\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\ . Change

AllowRemoteConnection to 1.


To enable state for all of the servers in a server farm to point back to a single state server, you need to change the IP address to reflect the IP address of the server running the Windows NT Service, and each of the server's machine keys must be identical. This last point is very important. Each server, by default, is set to auto-generate its own machine key. This machine key is used to encrypt data or to create unique serverspecific values for data (known as hashing).

The ID used for Session state is created using the machine key. Thus, for the key to be understood by all the servers in the farm, the servers need the same machine key. The machine key has other applications besides

sessionState and we will cover it in more detail later in the chapter.

Out-Of-Process – SQL Server

Configuring ASP.NET to support SQL Server for

Session state is just as simple as configuring the Windows Service. The only difference is that we will use SQL Server. To configure SQL Server, you need to run a T-SQL script that ships with ASP.NET –

InstallSqlState.sql . A T-SQL script (called

UninstallSqlState.sql ), to uninstall ASP.NET SQL Server support, is also included.





Note

ASP.NET ships with a lightweight version of SQL Server 2000 that has several limitations (such as limited connections, throttled transactions) but is a normal working version of SQL Server 2000 for all practical purposes. You can use this developer version of SQL Server 2000 for development purposes, but to deploy and use SQL Server for state management in a production server farm, use SQL Server 2000 Standard or Enterprise versions for optimal performance.


To run the

InstallSqlState.sql script, we will use a tool that ships with SQL Server (and MSDE);

OSQL.exe . OSQL allows us to apply a T-SQL script to a SQL Server. The

InstallSqlState.sql T-SQL script creates several stored procedures and creates several temporary databases for ASP.NET

Session to use.





Note

Version 1.1 of ASP.NET ships with another set of SQL Scripts for storing the session data in permanent SQL table (as opposed to using SQL Server temporary tables). These scripts are named

InstallPersistSqlState.sql and

UninstallPersistSqlState.sql . Use these scripts to setup replication or failover for Session data – SQL replication/failover support does not exist for data stored in SQL Server temporary tables.


The script only needs to be run once on any given SQL Server, and we will need

sa -level (administrator) access to run the script. To run the script, open a command prompt and navigate to the

\WINNT\Microsoft.NET\Framework\[version]\ directory and type:

> OSQL -S localhost -U sa -P <InstallSqlState.sql
1> 2> 3> 1> 2> 3> 4> 5> 6> 1> 2> 3> 4> 5> 6> 1> 2> 3> 4> 5> 1> 2> 3> 4> 5> 6> 7>
8> 1> 2> 3> 4> 5> 6> 7> 8> 1> 2> 3> 4> 5> 6> 7> 8> 1> 2> 3> 4> 5> 6> 7> 8> 9> 10>
11> 12> 13> 14> 15> 16> 17> 18> 19> 20> 21> 22> 23> 1> 2> 3> 4> The CREATE
DATABASE process is allocating 0.63 MB on disk 'ASPState'.
The CREATE DATABASE process is allocating 0.49 MB on disk 'ASPState_log'.
1> 2> 3> 1> 2> 3> 1> 2> 1> 2> 3> 4> 5> 6> 7> 8> 9> 10> 11> 12> 13> 1> 2> 3> 4> 5>
6> 7> 8> 9> 10> 11> 12> 13> 14> 15> 16> 17> 18> 19> 20> 21> 22> 23> 24> 25> 26>
27> 28> 29> 30> 31> 1> 2> 3> 4> 5> 6> 7> 1> 2> 3> (1 row affected)
Type added.
1> 2> 3> (1 row affected)
Type added.
1> 2> 3> (1 row affected)
Type added.
1> 2> 3> (1 row affected)
Type added.
1> 2> 3> (1 row affected)
Type added.
1> 2> 3> 4> 5> 6> 7> 8> 9> 10> 11> 12> 13> 14> 15> 16> 17> 18> 19> 20> 21> 22> 1>
2> 3> 4> 5> 6> 7> 8> 9> 10> 11> 12> 13> 14> 15> 16> 17> 18> 19> 20> 21> 22> 23>
24> 25> 26> 27> 28> 29> 30> 31> 32> 33> 34> 35> 36> 37> 1> 2> 3> 4> 5> 6> 7> 8> 9>
10> 11> 12> 13> 14> 15> 16> 17> 18> 19> 20> 21> 22> 23> 24> 25> 26> 27> 28> 29>
30> 31> 32> 33> 34> 35> 36> 37> 38> 39> 40> 41> 42>
. . . . . . .

Next, you need to change the configuration settings to use SQL Server (highlighted). First, you set

mode to

"SQLServer" and then configure the

sqlConnectionString to point to the server that has the TSQL script installed:

<configuration>
<system.web>
<sessionState

mode="SQLServer"
stateConnectionString="tcpip=127.0.0.1:42424"
stateNetworkTimeout="10"

sqlConnectionString="data source=127.0.0.1;

user id=session;password=&363test"
cookieless="false"
timeout="20"
/>
</system.web>
</configuration>






Note

Session data stored in SQL is inaccessible to other applications. It is serialized as a protected type and should not be read or modified by applications other than ASP.NET.






Important

ASP.NET accesses the data stored in SQL via stored procedures. By default, session data is stored in the

TempDB database. The stored procedures may be modified, for example, if we wished to store to tables other than

TempDB . However, this is an option best saved for DBAs.


From the developer's point of view, writing code that uses

Session in any of the preceding modes is completely transparent. However, we should briefly discuss choosing a mode, as the mode selection can impact on the performance of the application.

Choosing a Mode


There are three modes from which you can choose when building an application:



In-process (default):In-process will perform best because the

Session data is kept within the ASP.NET process, and local memory access will always be faster than having to go out-of- process. Additional reasons include web applications hosted on a single server, applications in which the user is guaranteed to be redirected to the correct server, or when

Session data is not critical (in the sense that it can be easily re-created).



Windows Service:This mode is best used when performance is important and there are multiple web servers servicing requests. With this out-of-process mode, you get the performance of reading from memory and the reliability of a separate process that manages the state for all servers.



SQL Server:This mode is best used when the reliability of the data is fundamental to the stability of the application, as the data is stored in SQL Server. The performance isn't as fast as the Windows Service, but the tradeoff is the higher level of reliability.



Now that we have examined the supported options for web farms, let's turn to another one of the great new features of ASP.NET

Session : support for clients that don't accept HTTP cookies.

Cookieless Session


Since HTTP is a stateless environment, both the client and the server need to maintain a key in order to maintain state across requests through

Session . This key is used to identify the client's

Session across requests. The server can then use the key to access the data stored for that user. By default, the server gives the client a key using an HTTP cookie. On subsequent requests to that server, the client will present the HTTP cookie and the server then has access to the session key.

However, some clients choose not to accept HTTP cookies for a variety of reasons, a common one being the perceived privacy issue. When this happens, the site has to either adapt and not support cookies (and

Session ), or build the application to not require the use of

Session . A third option, first provided with IIS 4, is an ISAPI filter that can extract the session ID out of the cookie and pass it as part of the URL. This concept is supported by ASP.NET as a first class feature. This feature is known as cookieless

Session state, and it works with any of the supported

mode options.





Note

Individual applications can be configured to support either cookie or cookieless states, but not both.


You can enable cookieless

Session support by simply setting a flag in the configuration system (highlighted):

<configuration>
<system.web>
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
stateNetworkTimeout="10"
sqlConnectionString="data source=127.0.0.1; user id=sa;password="

cookieless="true"
timeout="20"
/>
</system.web>
</configuration>


As with all configuration changes in ASP.NET, these settings are applied immediately. After changing cookieless from

false (the default) to

true , the session ID is embedded in the URL of the page, as shown in Figure 13-5. As you can see, the session ID

reqe3wvsxfoabvilmkmvq2p is embedded within the URL:


Figure 13-5:

The following source in Visual Basic .NET shows this. You will notice that no special changes have been made to the sourcecode to support embedding the

Session ID in the URL:


<Script runat=server>

Public Sub Session_Add(sender As Object, e As EventArgs)

Session("cart") = text1.Value

span1.InnerHtml = "Session data updated! <P>" + _

"Your session contains: <font color=red>" + _

Session("cart") + "</font>"

End Sub


Public Sub CheckSession(sender As Object, e As EventArgs)

If (Session("cart") Is Nothing) Then

span1.InnerHtml = "NOTHING, SESSION DATA LOST!"

Else

span1.InnerHtml = "Your session contains:" + _

"<font color=red>" + Session("cart") + "</font>"

End If

End Sub

</Script>

<form runat=server>

<input id=text1 type=text runat=server>

<input type=submit runat=server OnServerClick="Session_Add"

Value="Add to Session State">

<input type=submit runat=server OnServerClick="CheckSession"

Value="View Session State">

</form>

<a href=">C# Example</A>

<hr size=1>

<font size=6><span id=span1 runat=server/></font>


Additionally, for relative URLs (as viewed by the browser) within the page, such as:

<a href=">C# Example</a>

ASP.NET will automatically add the session ID into the URL. The client receives the following link:

<a href="/(yxxn2w555rn13henl2sxd055)/">C# Example</a>

Note that the ID is added directly after the name of the application root. In this example, you can see that

/Session is marked as an application. The new features for

Session state in ASP.NET are very powerful. You can configure

Session to be stored in a separate process from the ASP.NET worker process, which allows the

Session data to be available if a server farm and in the rare case that the web server crashes. In addition to the great support for out-of-process

Sessions state, support for cookieless

Session s has also been added. Cookieless session allows you to use

Session for clients that don't accept HTTP cookies. Next, let's look at a feature of ASP.NET that replaces

Response.Write debugging for ASP pages.

/ 244