Anda di halaman 1dari 4

Manage Session State on the Server

The .NET Framework offers several built-in, easy-to-use features that provide a clean approach to
server-side state management. Some of these features support state across Web farms (multiple
load-balancing Web servers).

Store State in the Session Object


The Session object provides a collection for storing all sorts of items about a user's session. The
first time a user requests a page in your application, ASP.NET creates a session environment for
this user on the Web server. ASP.NET exposes the Session object as a collection for you to store
and retrieve state information for this user. You use the Session object like any other collection to
store anything from simple data types to complex objects and structures. ASP.NET assigns a
unique ID for each session to isolate an individual user's private state information. Each active
ASP.NET session is identified and tracked using a 120-bit SessionID string containing URL-legal
ASCII characters. SessionID values are generated using an algorithm that guarantees
uniqueness so that sessions do not collide, and SessionID’s randomness makes it harder to guess
the session ID of an existing session.ASP.NET uses a temporary cookie (which is stored in client
RAM, then discarded when the user closes the browser) to pass the session ID between the
browser and the Web server. It's important to understand that only the session ID—a small value
—gets passed between client and server. The state information itself is stored on the Web server
in RAM without ever crossing the wire (see Figure 1).

Figure 1: Manage User State With Sessions.


ASP.NET stores each user's state information in a session environment in RAM on the Web server. ASP.NET
uses a temporary cookie or URL munging to pass the unique session ID between client and server. Your
application uses the Session object as a collection for accessing each user's state information.

After a period of inactivity from the client (20 minutes by default), user sessions time out and are
discarded from server RAM.

//to store information


Session[“myname”]= “Lloyd”;
//to retrieve information
myname=Session[“myname”];

Sessions don't work at all if the user has disabled cookies, because the Web server uses cookies
to pass the session ID. Fortunately, ASP.NET has decorated the Session object with two new
features that address these problems: cookieless sessions and out-of-process state management.
As the name implies, cookieless sessions enable the Session object even if the user turns off
cookie support in the browser. Enabling this feature is as simple as setting an attribute in the
web.config file:
<sessionState
mode="Off|InProc|StateServer|SqlServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="true|false"
timeout="20"
/>

Then, ASP.NET auto-magically inserts the session ID into the URL of every link in your application,
rather than using a cookie to pass the session ID back and forth over the wire. For example,
http://localhost/PageA.aspx becomes http://localhost/(w1fmnnqzif4k1bnuarqrwinq)/PageA.aspx.

In the past, only few developers could employ this technique (commonly referred to as "URL-
munging") through tedious coding. Now, ASP.NET makes it easy, elegant, and accessible to all.
ASP.NET is smart enough to insert the session ID into the URLs of every anchor tag and form
action in your application. Cookieless sessions guarantee that your application functions,
regardless of cookie support on the client. If you need to "manufacture" a URL for passing to an
external application, you can use the Response.ApplyAppPathModifier method, which accepts any
URL and "munges" it with the session ID. In this way, the external application can call back into
your application with the appropriate session ID:
string sMungedUrl = Response.ApplyAppPathModifier(“PageA.aspx");

However, if you request Another page without the embedded Session ID


(http://localhost/WebForm2.aspx), the state is lost and the ASP.NET framework issues a new
Session Id. Also

1. Fully qualified URLs in the response.redirect, server.transfer, and FORM action tags cannot be
used. Here is an example of a fully qualified.

2. Root addressing can also cause problems with response.redirect, server.transfer, and FORM
action tags. In other words /home/default.aspx cannot be used. You'd have to reference it using
relative addressing. For example, home/default.aspx

Scale Up or Scale Out


Out-of-process state management deals with the issue of scalability. You have two ways to handle
the demand of many sessions with lots of state information. The first is to "scale up"—add more
RAM and more CPUs to the server until you hit the ceiling on maximum memory and processors.
The second is to "scale out"—add more servers. A scaled-out configuration is commonly referred
to as a Web farm, where each server in the farm runs the same ASP.NET application and the
collection of servers appears to the outside world as a single site. This provides dynamic load-
balancing by distributing client demand evenly across a set of servers.
Classic ASP applications can't take full advantage of Web farms. Session state is stored in RAM, so
the user must always be directed to the server that stores his state information. Once a user's
initial page request hits a server, the user is tied to that particular server for all subsequent page
requests.
Figure 2: Scale Up With Out-Of-Process Sessions.
You can configure a Web farm to load-balance a demanding user base. ASP.NET can store session
information on a dedicated state server either in RAM (using the ASP.NET State Service) or on disk (using
SQL Server). Client requests are satisfied by any server in the farm, which in turn communicates with the
state server for session information.

ASP.NET solves this problem by providing "out-of-process" state management. This feature
removes session state from the Web server and places it in another process on another machine
called the state server (see Figure 2). The Web servers in the farm communicate with the state
server to store and retrieve session information. True load-balancing is achieved, and any Web
server in the farm can process any page request issued by any client at any time. Furthermore,
Web servers can be taken down and brought back online without disrupting active user sessions.
ASP.NET generates unique IDs for each machine in the network automatically, by default. You
configure a Web farm by setting each server's machine key to the same value. Edit the
machine.config file (located in the C:\winnt\Microsoft.NET\Framework\vn.n.n\CONFIG directory)
on each server and find the machineKey tag. Set the validationKey and decryptionKey attributes
to a hex value (any value will do, as long as you use the same value on all machines):

<machineKey validationKey="0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"
decryptionKey="FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210"
:
/>

You have two options for configuring a state server: Use the ASP.NET State Service or use SQL
Server. The ASP.NET State Service uses RAM on the state server to store session information for
all Web servers in the farm. This service is off by default; in a production environment, set its
startup mode to "Automatic" in the Computer Management services console. Then, set two
attributes in the web.config file of each Web server in the farm to enable the feature and identify
the state server's IP address (leave the port at the default value of 42424):
<sessionState mode="StateServer"
stateConnectionString="tcpip=192.168.0.7:42424"
...
/>
Achieve Maximum Scalability
The SQL Server option stores session information in a database on the state server, and is
available only if you have a SQL Server license. Although you incur a slight performance penalty
by accessing a database rather than RAM, this option provides the greatest scalability, because
database sizes are virtually unlimited compared with RAM. SQL Server uses caching extensively,
so recently accessed state information is frequently retrieved from RAM anyway, which boosts
performance. Furthermore, ASP.NET is smart enough to use a varbinary column for state
information smaller than 7,000 bytes, and it uses a less efficient image column only if the state
information exceeds 7,000 bytes. One caveat: You must ensure that any objects you store in
Session are serializable if you want to use this feature.

Use Query Analyzer to execute the script file InstallSqlState.sql (located in the
C:\winnt\Microsoft.NET\Framework\vn.n.n folder) to create the stored procedures ASP.NET
requires for using SQL Server. ASP.NET uses tempdb to store session information for performance
reasons, so sessions are lost if SQL Server goes down. You can modify the script (at your own
risk) to use another database if you want truly durable sessions that survive server reboots.
Set two attributes in the web.config file of each of the farm's Web servers to enable the feature
and identify SQL Server's IP address:
<sessionState mode="SqlServer"
sqlConnectionString="data source=192.168.0.7;Trusted_Connection=yes"
...
/>

You can improve performance slightly for pages that only need to read but not write Session
variables by including the EnableSessionState="ReadOnly" attribute in the <%@ Page %> tag
directive. You can also turn off sessions for pages that don't need them by specifying
EnableSessionState="False" for even better performance of those pages.

Summary
Below is a quick summary of the different modes of session state available in ASP.NET:

Storage location

• InProc - session kept as live objects in web server (aspnet_wp.exe). Use "cookieless"
configuration in web.config to "munge" the sessionId onto the URL (solves
cookie/domain/path RFC problems too!)
• StateServer - session serialized and stored in memory in a separate process
(aspnet_state.exe). State Server can run on another machine
• SQLServer - session serialized and stored in SQL server

Performance

• InProc - Fastest, but the more session data, the more memory is consumed on the web
server, and that can affect performance.
• StateServer - When storing data of basic types (e.g. string, integer, etc), in one test
environment it's 15% slower than InProc. However, the cost of serialization/deserialization
can affect performance if you're storing lots
of objects. You have to do performance testing for your own scenario.
• SQLServer - When storing data of basic types (e.g. string, integer, etc), in one test
environment it's 25% slower than InProc. Same warning about serialization as in
StateServer.

Anda mungkin juga menyukai