Thursday, November 20, 2008

Session management in ASP.NET

Session Management


HTTP is stateless, means that the web pages don’t know if the requests are from the same client and pages are recreated and destroyed every trip to the server. Therefore, state management is important for web applications.


All data that needs to be available to the application across different requests within the same session is called session state or session state data. For storing such data between requests, there are in general two possibilities:

· Sending the state information back to the client. With the next request the current state is transmitted to the server again.

· Keeping the necessary data structures on the server. No session data (except the referencing identifier) is transmitted to the client.

1.1.1 Drawbacks of managing state information in client

· Sending the session state data back to the client is generally not recommended. From a security perspective, the main problem is that the session state can easily be manipulated on the client side if it is not protected appropriately.

· In scenarios where session state information must be transmitted back to the client, it is generally possible to sign all transmitted session state information in order to prevent changes on the client side. When the server receives session state information within requests from the client, it can check the signature in order to verify that the data was not altered.

· A functional drawback is that the size of the information that can be stored by round-tripping it to the client side is limited through the available bandwidth. For session state data that consists of only a few bytes this does not matter. However, in scenarios with larger session state data structures, re-transmitting them with each request becomes impractical.

1.1.2 State management in server

Keeping the session state strictly on the server is the recommended solution.

· Session state is stored in the server RAM.

· Session state is serialized and written to a persistent storage.

· Storing mechanism for session is irrelevant from a session management security point of view.

· Ensure that the session state information is sufficiently protected against illegal access on the server side.

1.1.3 Session IDs

Typically, the process of managing the state of a web-based client is through the use of session IDs. Session IDs are used by the application to uniquely identify a client browser, while background (server-side) processes are used to associate the session ID with the existing state of the user. Session state management is a key element of Web application design. ASP.NET contains a session state support service that is flexible and scalable.

1.2 Methods of implementing Session States in ASP .NET

There are three session state modes for ASP.NET Applications. Each mode offers varying degrees of performance and scalability as described in the following list:

1.2.1 InProc

The in-process store provides the fastest access to session state. There is no serialization or marshaling costs involved because state is maintained within the managed memory of the ASP.NET process. When the process recycles, the state data is lost, although we can disable process recycling in IIS if process recycling affects the application.


· Limits application scalability

· Cannot use it in conjunction with multiple worker processes.

· Also, high numbers of large or concurrent sessions can cause application to run out of memory.

1.2.2 State Server

The session state service, a Microsoft Win32® service, can be installed on local Web server or on a remote server that is accessible by all Web servers in a Web farm.


· High Scalability.


· Performance is reduced in comparison to the in-process provider because of the additional serialization and marshaling that is required to transfer the state to and from the state store.

1.2.3 SQL Server:

Microsoft SQL Server provides a highly scalable and easily available solution. SQL Server is a solution that is well-suited to large amounts of session state.

The serialization and marshalling costs are the same as the costs for the session state service, although overall performance is slightly lower.

SQL Server provides clustering for failover, although this is not supported in the default configuration for session state. To enable clustering for failover, we have to apply configuration changes, and the session data must be stored in a non temporary table.

1.3 Administering Session states in server

Developers can use Session state in applications and leave the implementation up to the administrators. When developer creates an ASP.NET application on his development machine, he can use in-process session state. Then when the application is deployed to a production server Web farm, an administrator can change session state to use either the ASP.NET State service or to host the session data in SQL Server. All of these options are transparent to the application. A simple setting in Web.Config makes the change in session state.

If your application does not require the ASP.NET session state services, turn it off. You can do this on a single page or for an entire application. You can disable session state in a page by adding EnableSessionState="false" in the Page directive like this:

<%@ Page Language="C#" EnableSessionState="false" AutoEventWireup="false" Codebehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1"%>

You can also totally disable session state for an application by setting mode=”Off” in Web.Config like this:

mode="Off" stateConnectionString="tcpip="

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


timeout="20" />

1.4 Why web farms?

Scalability and high availability is the answer.

Once a web application has gained enough business traction to be handling thousands of concurrent users and hundreds of requests per second, it inevitably bumps up against the performance limits imposed by running on a single server.

1.4.1 Performance limits of a single server:

· Even we do caching, session state accumulate to the point where they tax available memory, causing frequent processor-intensive garbage collection events and even recycling of worker processes, with loss of in-memory data.

· The available ASP.NET threads become exhausted and requests start to queue, eventually leading to error conditions.

· The server may not be available to fulfill the request all time.

The solution is to spread the load across clustered application servers, usually referred to as a “web farm.”

The move from a single server to a web farm often causes significant disruptions, unless the application has been architected from the beginning to support load-balanced clustered request processing. Without explicit planning, many applications end up with hidden dependencies on resource affinity.

1.4.2 Resource affinity is ASP.NET Applications in web farms:-

“Resource affinity” refers to a requirement for code to run on a particular thread, CPU, component instance or server. The Session is a resource. The most common affinity problem in ASP.NET applications is the use of in-process session state, which assumes that all requests from a single user session will be processed on the same web server.

1.4.3 Resolving session affinity in ASP.NET Applications in web farms:

· Route all requests to the server where the session originated. This significantly reduces load balancing efficiency, and it impairs the ability of the ASP.NET application to tolerate failures such as recycling the worker-thread process under extreme load.

· Storing session state in a shared location, this can be accessed by any of the web servers in the farm.

1.4.4 Session sharing in web farms:

ASP.NET has built-in support for storing session state out-of-process, either in a database or in the memory space of a designated state server.


· By moving session state out-of-process, the dependency of a given user on a given web server is reduced: if that web server fails or recycles, the user’s current session data is not lost.

1.5 Implementing out-of-process session state storage

For out-of-process state storage to be possible, all .NET objects stored in session state must be serializable. Because .NET classes are not serializable by default, this often means recoding, either to add attributes to user-defined classes or to use serializable built-in classes instead of ones that are not serializable.

1.5.1 State Server

State Server is simple, free software available with ASP.NET for storing session state data. It can be run directly on the web server, at least providing protecting from worker-thread recycling, or it can be run in a central location to get the full benefits of non-affinity.

Limitations of State Server:

· When using State Server remotely—every request/response pair involves two trips to the State Server, one to retrieve the session state data at the beginning of the generation of the response and another to return the modified session state data when the response is completed.

· When it fails or restarted all the session data is lost

1.5.2 SQL Server

SQL Server is a popular choice for out-of-process session state storage.


· The application is already using SQL Server for retrieval and storage of data related to the application.

· High availability features such as clustering to protect session state data in case of failure.


· The performance of SQL Server is even slower than that of State Server.

· SQL Server is designed to be a highly reliable and secure transactional database, so the processing of session data takes significantly longer.

· SQL Server also requires the same extra pair of network trips that State Server does: at the beginning and end-of-page processing.

Beginners IV

ASP Response Object

The ASP Response object is used to send output to the user from the server.

Response Object

The ASP Response object is used to send output to the user from the server. Its collections, properties, and methods are described below:





Sets a cookie value. If the cookie does not exist, it will be created, and take the value that is specified





Specifies whether to buffer the page output or not


Sets whether a proxy server can cache the output generated by ASP or not


Appends the name of a character-set to the content-type header in the Response object


Sets the HTTP content type for the Response object


Sets how long (in minutes) a page will be cached on a browser before it expires


Sets a date and time when a page cached on a browser will expire


Indicates if the client has disconnected from the server


Appends a value to the PICS label response header


Specifies the value of the status line returned by the server





Adds a new HTTP header and a value to the HTTP response


Adds a string to the end of the server log entry


Writes data directly to the output without any character conversion


Clears any buffered HTML output


Stops processing a script, and returns the current result


Sends buffered HTML output immediately


Redirects the user to a different URL


Writes a specified string to the output

ASP Request Object


The ASP Request object is used to get information from the user.

QueryString Collection Examples

Send query information when a user clicks on a link
This example demonstrates how to send some extra query information to a page within a link, and retrieve that information on the destination page (which is, in this example, the same page).

A QueryString collection in its simplest use
This example demonstrates how the QueryString collection retrieves the values from a form. The form uses the GET method, which means that the information sent is visible to everybody (in the address field). The GET method also limits the amount of information that can be sent.

How to use information from forms
This example demonstrates how to use the values retrieved from a form. We use the QueryString collection. The form uses the get method.

More information from a form
This example demonstrates what the QueryString contains if several input fields have the same name. It shows how to separate input fields with equal names from each other. It also shows how to use the Count keyword to count the "name" property. The form uses the get method.

Form Collection Examples

A form collection in its simplest use
This example demonstrates how the Form collection retrieves the values from a form. The form uses the POST method, which means that the information sent is invisible to others, and it has no limits (you can send a large amount of information).

How to use information from forms
This example demonstrates how to use the values retrieved from a form. We use the Form collection. The form uses the post method.

More information from a form
This example demonstrates what the Form collection contains if several input fields have the same name. It shows how to separate input fields with equal names from each other. It also shows how to use the Count keyword to count the "name" property. The form uses the post method.

A form with radio buttons
This example demonstrates how to interact with the user through radio buttons, with the Form collection. The form uses the post method.

A form with checkboxes
This example demonstrates how to interact with the user through checkboxes, with the Form collection. The form uses the post method.

Other Examples

Get the server variables
This example demonstrates how to find out the visitors (yours) browser type, IP address, and more with the ServerVariables collection.

Create a welcome cookie
This example demonstrates how to create a Welcome Cookie with the Cookies Collection.

Find the total number of bytes the user sent
This example demonstrates how to use the TotalBytes property to find out the total number of bytes the user sent in the Request object.

Request Object

When a browser asks for a page from a server, it is called a request. The ASP Request object is used to get information from the user. Its collections, properties, and methods are described below:





Contains all the field values stored in the client certificate


Contains all the cookie values sent in a HTTP request


Contains all the form (input) values from a form that uses the post method


Contains all the variable values in a HTTP query string


Contains all the server variable values





Returns the total number of bytes the client sent in the body of the request





Retrieves the data sent to the server from the client as part of a post request and stores it in a safe array

Your name:

dim fname
If fname<>"" Then
Response.Write("Hello " & fname & "!
Response.Write("How are you today?")
End If

If Response.IsClientConnected=true then
Response.Write("The user is still connected!")
Response.Write("The user is not connected!")
end if

ASP Quick Reference


ASP Quick Reference from W3Schools. Print it, and fold it in your pocket.

Basic Syntax

ASP scripts are surrounded by <% and %>. To write some output to a browser:

<% response.write("Hello World!") %>

The default language in ASP is VBScript. To use another scripting language, insert a language specification at the top of the ASP page:

<%@ language="javascript" %>


Forms and User Input

Request.QueryString is used to collect values in a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send.

Request.Form is used to collect values in a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

ASP Cookies

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests for a page with a browser, it will send the cookie too.

The Response.Cookies command is used to create cookies:

Response.Cookies("firstname").Expires="May 10,2002"

Note: The Response.Cookies command must appear BEFORE the tag!

The "Request.Cookies" command is used to retrieve a cookie value:

response.write("Firstname=" & fname)

Including Files

You can insert the content of one ASP file into another ASP file before the server executes it, with the #include directive. The #include directive is used to create functions, headers, footers, or elements that will be reused on multiple pages



Use the virtual keyword to indicate a path beginning with a virtual directory. If a file named "" resides in a virtual directory named /html, the following line would insert the contents of "":

Use the file keyword to indicate a relative path. A relative path begins with the directory that contains the including file. If you have a file in the html directory, and the file "" resides in html\headers, the following line would insert "" in your file:

Use the file keyword with the syntax (..\) to include a file from a higher-level directory.


The Global.asa file is an optional file that can contain declarations of objects, variables, and methods that can be accessed by every page in an ASP application.

Note: The Global.asa file must be stored in the root directory of the ASP application, and each application can only have one Global.asa file.

The Global.asa file can contain only the following:

Application events

Session events


TypeLibrary declarations

the #include directive

Application and Session Events

In Global.asa you can tell the application and session objects what to do when the application/session starts and what to do when the application/session ends. The code for this is placed in event handlers. Note: We do not use <% and %>, to insert scripts in the Global.asa file, we have to put the subroutines inside the HTML


It is also possible to create objects with session or application scope in Global.asa by using the tag. Note: The tag should be outside the

Your Title