ONE Active Server Pages Product Home Page Developer Site Version


Remarks: ASP Session Object

Values can be stored in the Session object. Information stored in the Session object is available for the entire session and has session scope. The following script demonstrates how two types of variables are stored:

Session("username") = "Janine"
Session("age") = 42

If you are using VBScript as your scripting language, you must use the Set keyword to store an object in the Session object, as shown in the following example:

<% Set Session("Obj1") = Server.CreateObject("MyComponent") %>

You can then call the methods and properties of Obj1 on subsequent Web pages by using the following syntax:

<% Session("Obj1").MyObjMethod %>

As an alternative, you can extract a local copy of the object:

Set MyLocalObj = Session("Obj1")

A built-in object cannot be stored in a Session object. Each of the following lines will return an error:

Set Session("var1") = Session
Set Session("var2") = Request
Set Session("var3") = Response
Set Session("var4") = Server
Set Session("var5") = Application

Before you store an object in the Session object, you must know the threading model it uses. Only objects marked as both free and apartment-threaded can be stored in the Session object.

The Session object is implemented as a collection. If you store an array in an Session object, you should not attempt to alter elements of the stored array directly. For example, the following script does not work:

Session("StoredArray") (3) = "new value"

Instead of storing the value "new value" in StoredArray(3), the value is stored in the Session collection, overwriting any information stored at Session(3).

See ASP Application Object Examples for an example of storing an array.