Szerkesztés

Megosztás a következőn keresztül:


HttpSessionState Class

Definition

Provides access to session-state values as well as session-level settings and lifetime management methods.

public ref class HttpSessionState sealed : System::Collections::ICollection
public sealed class HttpSessionState : System.Collections.ICollection
type HttpSessionState = class
    interface ICollection
    interface IEnumerable
Public NotInheritable Class HttpSessionState
Implements ICollection
Inheritance
HttpSessionState
Implements

Examples

The following code example sets and retrieves values from session state.

Important

This example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Collections" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  public void Page_Load(object sender, EventArgs args)
  {
    if (!IsPostBack)
    {
      if (Session["address"] == null)
      {
        enterUserInfoPanel.Visible = true;
        userInfoPanel.Visible = false;
      }
      else
      {
        enterUserInfoPanel.Visible = false;
        userInfoPanel.Visible = true;

        SetLabels();
      }
    }
  }

  protected void SetLabels()
  {
    firstNameLabel.Text = Session["firstName"].ToString();
    lastNameLabel.Text = Session["lastName"].ToString();
    addressLabel.Text = Session["address"].ToString();
    cityLabel.Text = Session["city"].ToString();
    stateOrProvinceLabel.Text = Session["stateOrProvince"].ToString();
    zipCodeLabel.Text = Session["zipCode"].ToString();
    countryLabel.Text = Session["country"].ToString();
  }

  protected void EnterInfoButton_OnClick(object sender, EventArgs e)
  {
    Session["firstName"] = Server.HtmlEncode(firstNameTextBox.Text);
    Session["lastName"] = Server.HtmlEncode(lastNameTextBox.Text);
    Session["address"] = Server.HtmlEncode(addressTextBox.Text);
    Session["city"] = Server.HtmlEncode(cityTextBox.Text);
    Session["stateOrProvince"] = Server.HtmlEncode(stateOrProvinceTextBox.Text);
    Session["zipCode"] = Server.HtmlEncode(zipCodeTextBox.Text);
    Session["country"] = Server.HtmlEncode(countryTextBox.Text);

    enterUserInfoPanel.Visible = false;
    userInfoPanel.Visible = true;

    SetLabels();
  }

  protected void ChangeInfoButton_OnClick(object sender, EventArgs args)
  {
    enterUserInfoPanel.Visible = true;
    userInfoPanel.Visible = true;
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <meta http-equiv="Content-Type" content="text/html" />
  <title>User Information</title>
</head>
<body>
  <form id="form1" runat="server">
    <h3>
      User information</h3>
    <asp:Label ID="Msg" ForeColor="maroon" runat="server" /><br />
    <asp:Panel ID="enterUserInfoPanel" runat="server">
      <table cellpadding="3" border="0">
        <tr>
          <td>
            First name:</td>
          <td>
            <asp:TextBox ID="firstNameTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            Last name:</td>
          <td>
            <asp:TextBox ID="lastNameTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            Address:</td>
          <td>
            <asp:TextBox ID="addressTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            City:</td>
          <td>
            <asp:TextBox ID="cityTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            State or Province:</td>
          <td>
            <asp:TextBox ID="stateOrProvinceTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            Zip Code/Postal Code:</td>
          <td>
            <asp:TextBox ID="zipCodeTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            Country:</td>
          <td>
            <asp:TextBox ID="countryTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            &nbsp;</td>
          <td>
            <asp:Button ID="enterInfoButton" runat="server" Text="Enter user information" OnClick="EnterInfoButton_OnClick" /></td>
        </tr>
      </table>
    </asp:Panel>
    <asp:Panel ID="userInfoPanel" runat="server">
      <table cellpadding="3" border="0">
        <tr>
          <td>
            Name:</td>
          <td>
            <asp:Label ID="firstNameLabel" runat="server" />
            <asp:Label ID="lastNameLabel" runat="server" />
          </td>
        </tr>
        <tr>
          <td valign="top">
            address:</td>
          <td>
            <asp:Label ID="addressLabel" runat="server" /><br />
            <asp:Label ID="cityLabel" runat="server" />,
            <asp:Label ID="stateOrProvinceLabel" runat="server" />
            <asp:Label ID="zipCodeLabel" runat="server" /><br />
            <asp:Label ID="countryLabel" runat="server" />
          </td>
        </tr>
        <tr>
          <td>
            &nbsp;</td>
          <td>
            <asp:Button ID="changeInfoButton" runat="server" Text="Change user information" OnClick="ChangeInfoButton_OnClick" /></td>
        </tr>
      </table>
    </asp:Panel>
  </form>
</body>
</html>

<%@ Page Language="VB" %>

<%@ Import Namespace="System.Collections" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  Public Sub Page_Load(ByVal sender As Object, ByVal args As EventArgs)
    If Not IsPostBack Then
      If Session("Address") Is Nothing Then
        EnterUserInfoPanel.Visible = True
        UserInfoPanel.Visible = False
      Else
        EnterUserInfoPanel.Visible = False
        UserInfoPanel.Visible = True
        
        SetLabels()
      End If
    End If
  End Sub
  
  Protected Sub SetLabels()
    FirstNameLabel.Text = Session("FirstName").ToString()
    LastNameLabel.Text = Session("LastName").ToString()
    AddressLabel.Text = Session("Address").ToString()
    CityLabel.Text = Session("City").ToString()
    StateOrProvinceLabel.Text = Session("StateOrProvince").ToString()
    ZipCodeLabel.Text = Session("ZipCode").ToString()
    CountryLabel.Text = Session("Country").ToString()
  End Sub
  
  Protected Sub EnterInfoButton_OnClick(ByVal sender As Object, ByVal args As EventArgs)
    Session("FirstName") = Server.HtmlEncode(FirstNameTextBox.Text)
    Session("LastName") = Server.HtmlEncode(LastNameTextBox.Text)
    Session("Address") = Server.HtmlEncode(AddressTextBox.Text)
    Session("City") = Server.HtmlEncode(CityTextBox.Text)
    Session("StateOrProvince") = Server.HtmlEncode(StateOrProvinceTextBox.Text)
    Session("ZipCode") = Server.HtmlEncode(ZipCodeTextBox.Text)
    Session("Country") = Server.HtmlEncode(CountryTextBox.Text)
    
    EnterUserInfoPanel.Visible = False
    UserInfoPanel.Visible = True
    
    SetLabels()
  End Sub
  
  Protected Sub ChangeInfoButton_OnClick(ByVal sender As Object, ByVal args As EventArgs)
    EnterUserInfoPanel.Visible = True
    UserInfoPanel.Visible = False
  End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <meta http-equiv="Content-Type" content="text/html" />
  <title>User Information</title>
</head>
<body>
  <form id="form1" runat="server">
    <h3>
      User information</h3>
    <asp:Label ID="Msg" ForeColor="maroon" runat="server" /><br />
    <asp:Panel ID="EnterUserInfoPanel" runat="server">
      <table cellpadding="3" border="0">
        <tr>
          <td>
            First name:</td>
          <td>
            <asp:TextBox ID="FirstNameTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            Last name:</td>
          <td>
            <asp:TextBox ID="LastNameTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            Address:</td>
          <td>
            <asp:TextBox ID="AddressTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            City:</td>
          <td>
            <asp:TextBox ID="CityTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            State or Province:</td>
          <td>
            <asp:TextBox ID="StateOrProvinceTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            Zip Code/Postal Code:</td>
          <td>
            <asp:TextBox ID="ZipCodeTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            Country:</td>
          <td>
            <asp:TextBox ID="CountryTextBox" runat="server" /></td>
        </tr>
        <tr>
          <td>
            &nbsp;</td>
          <td>
            <asp:Button ID="EnterInfoButton" runat="server" Text="Enter user information" OnClick="EnterInfoButton_OnClick" /></td>
        </tr>
      </table>
    </asp:Panel>
    <asp:Panel ID="UserInfoPanel" runat="server">
      <table cellpadding="3" border="0">
        <tr>
          <td>
            Name:</td>
          <td>
            <asp:Label ID="FirstNameLabel" runat="server" />
            <asp:Label ID="LastNameLabel" runat="server" />
          </td>
        </tr>
        <tr>
          <td valign="top">
            Address:</td>
          <td>
            <asp:Label ID="AddressLabel" runat="server" /><br />
            <asp:Label ID="CityLabel" runat="server" />,
            <asp:Label ID="StateOrProvinceLabel" runat="server" />
            <asp:Label ID="ZipCodeLabel" runat="server" /><br />
            <asp:Label ID="CountryLabel" runat="server" />
          </td>
        </tr>
        <tr>
          <td>
            &nbsp;</td>
          <td>
            <asp:Button ID="ChangeInfoButton" runat="server" Text="Change user information" OnClick="ChangeInfoButton_OnClick" /></td>
        </tr>
      </table>
    </asp:Panel>
  </form>
</body>
</html>

Remarks

ASP.NET provides session-state management to enable you to store information associated with a unique browser session across multiple requests. You can store a collection of values referenced by a key name or by numerical index. Access to session values and functionality is available using the HttpSessionState class, which is accessible through the Session property of the current HttpContext, or the Session property of the Page.

Session data is associated with a specific browser session using a unique identifier. By default, this identifier is stored in a non-expiring session cookie in the browser, but you can also configure your application to store the session identifier in the URL by setting the cookieless attribute to true or UseUri in the sessionState element of your application configuration. You can have ASP.NET determine whether cookies are supported by the browser by specifying a value of UseDeviceProfile for the cookieless attribute. You can also have ASP.NET determine whether cookies are enabled for the browser by specifying a value of AutoDetect for the cookieless attribute. If cookies are supported when UseDeviceProfile is specified, or enabled when AutoDetect is specified, then the session identifier will be stored in a cookie; otherwise the session identifier will be stored in the URL.

Sessions are started during the first request and session values will persist as long as a new request is made by the browser before the number of minutes specified in the Timeout property pass. When a new session begins, the session Start event is raised. You can use this event to perform any additional work at the start of a session, such as setting default session values. When a session times out, the Abandon method is called, or the ASP.NET application is shut down, the session End event is raised. You can use this event to perform any necessary cleanup. The End event is raised only when the session state mode is set to InProc.

To improve performance, sessions that use cookies do not allocate session storage until data is actually stored in the Session object. For more information, see the SessionID property.

Session state does not persist across ASP.NET application boundaries. If a browser navigates to another application, the session information is not available to the new application.

Session values are stored in memory on the Web server, by default. You can also store session values in a SQL Server database, an ASP.NET state server, or a custom server. This enables you to preserve session values in cases where the ASP.NET or IIS process or the ASP.NET application restarts and to make session values available across all the servers in a Web farm. This behavior is configured by setting the mode attribute to a valid SessionStateMode value in the sessionState element of your application configuration. For more information, see Session-State Modes.

Alternatives to session state include application state (see the Application property) and the ASP.NET cache (see the System.Web.Caching namespace), which store variables that can be accessed by all users of an ASP.NET application; the ASP.NET profile (see the System.Web.Profile namespace), which persists user values in a data store without expiring them using a time-out; ASP.NET System.Web.UI.WebControls, which persist control values in the ViewState; Cookies; the QueryString property; and fields on an HTML form that are available from an HTTP POST using the Form collection. For more details on the differences between session state and other state-management alternatives, see ASP.NET State Management Recommendations.

Properties

CodePage

Gets or sets the character-set identifier for the current session.

Contents

Gets a reference to the current session-state object.

CookieMode

Gets a value that indicates whether the application is configured for cookieless sessions.

Count

Gets the number of items in the session-state collection.

IsCookieless

Gets a value indicating whether the session ID is embedded in the URL or stored in an HTTP cookie.

IsNewSession

Gets a value indicating whether the session was created with the current request.

IsReadOnly

Gets a value indicating whether the session is read-only.

IsSynchronized

Gets a value indicating whether access to the collection of session-state values is synchronized (thread safe).

Item[Int32]

Gets or sets a session value by numerical index.

Item[String]

Gets or sets a session value by name.

Keys

Gets a collection of the keys for all values stored in the session-state collection.

LCID

Gets or sets the locale identifier (LCID) of the current session.

Mode

Gets the current session-state mode.

SessionID

Gets the unique identifier for the session.

StaticObjects

Gets a collection of objects declared by <object Runat="Server" Scope="Session"/> tags within the ASP.NET application file Global.asax.

SyncRoot

Gets an object that can be used to synchronize access to the collection of session-state values.

Timeout

Gets or sets the amount of time, in minutes, allowed between requests before the session-state provider terminates the session.

Methods

Abandon()

Cancels the current session.

Add(String, Object)

Adds a new item to the session-state collection.

Clear()

Removes all keys and values from the session-state collection.

CopyTo(Array, Int32)

Copies the collection of session-state values to a one-dimensional array, starting at the specified index in the array.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator()

Returns an enumerator that can be used to read all the session-state variable names in the current session.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
Remove(String)

Deletes an item from the session-state collection.

RemoveAll()

Removes all keys and values from the session-state collection.

RemoveAt(Int32)

Deletes an item at a specified index from the session-state collection.

ToString()

Returns a string that represents the current object.

(Inherited from Object)

Extension Methods

Cast<TResult>(IEnumerable)

Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Enables parallelization of a query.

AsQueryable(IEnumerable)

Converts an IEnumerable to an IQueryable.

Applies to

See also