ASP Session Management

FDN » ASP & VBScript » ASP Session Management

ASP Session Management

The ASP Session object stores user-specific data on the server. A unique session ID (stored in a cookie named ASPSESSIONID) identifies each user.

Basic Usage

<%
' Store values in the session
Session("UserID")   = 42
Session("Username") = "jsmith"
Session("Role")     = "admin"
Session("LoginTime") = Now()

' Read values
Dim strUser
strUser = Session("Username")
If strUser = "" Then
    Response.Redirect "login.asp"
End If

' Remove a single value
Session.Contents.Remove "LoginTime"

' Clear all session data
Session.Abandon
%>

Session Configuration

PropertyDefaultDescription
Session.Timeout20 minutesIdle timeout before the session expires
Session.SessionID(auto)Unique identifier for the session
Session.CodePageSystem defaultCharacter encoding for the session

Global.asa Events

The Global.asa file handles application and session lifecycle events:

<SCRIPT LANGUAGE="VBScript" RUNAT="Server">
Sub Session_OnStart
    Session.Timeout = 30
    Session("StartTime") = Now()
    Application.Lock
    Application("ActiveSessions") = Application("ActiveSessions") + 1
    Application.UnLock
End Sub

Sub Session_OnEnd
    Application.Lock
    Application("ActiveSessions") = Application("ActiveSessions") - 1
    Application.UnLock
End Sub

Sub Application_OnStart
    Application("ActiveSessions") = 0
    Application("AppStartTime")   = Now()
End Sub
</SCRIPT>

Scalability Considerations

  • Session state is server-affinity: In a web farm, the user must always hit the same server. Use sticky sessions (IP affinity) on the load balancer, or avoid Session entirely.
  • Do not store COM objects in Session: Objects must be apartment-threaded, which serializes requests for that user. Store primitive data types only.
  • Cookie dependency: If the client does not accept cookies, ASP session tracking does not work. There is no built-in cookieless session support in classic ASP (unlike ASP.NET).
  • Alternative: Store session data in a database keyed by a custom token. This scales across servers and survives IIS restarts.
« Developer Network ‹ Database Access with ADO Server-Side Form Validation ›