共用方式為


How to: Read Values from Session State

This example accesses the Item property to retrieve the values in session state.

Example

Dim firstName as String = CType(Session.Item("FirstName"), String)
Dim lastName as String = CType(Session.Item("LastName"), String)
Dim city as String = CType(Session.Item("City"), String)
string firstName = (string)(Session["First"]);
string lastName = (string)(Session["Last"]);
string city = (string)(Session["City"]);

Compiling the Code

This example requires:

  • A Web Forms page or class that has access to the current request context using the Current property in an ASP.NET application that has session state enabled.

Robust Programming

No exception is thrown if you attempt to get a value out of session state that does not exist. To be sure that the value you want is in session state, check first for the existence of the object with a test such as the following:

If Session.Item("FirstName") Is Nothing Then
    ' No such value in session state, take appropriate action.
End If
if (Session["City"] == null) 
    // No such value in session state; take appropriate action.

If you attempt to use a nonexistent session state entry in some other way (for example, to examine its type), a NullReferenceException exception is thrown.

Session values are of type Object. In Visual Basic, if you set Option Strict On, you must cast from type Object to the appropriate type when getting values out of session state, as shown in the example. In C#, you should always cast to the appropriate type when reading session values.

See Also

Tasks

How to: Read Values from View State
How to: Save Values in View State

Concepts

ASP.NET State Management Overview
ASP.NET State Management Recommendations

Other Resources

ASP.NET State Management