HttpSessionState HttpSessionState HttpSessionState HttpSessionState Class

定义

提供对会话状态值以及会话级别设置和生存期管理方法的访问。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
继承
HttpSessionStateHttpSessionStateHttpSessionStateHttpSessionState
实现

示例

下面的代码示例设置并从会话状态中检索值。The following code example sets and retrieves values from session state.

重要

此示例具有一个接受用户输入的文本框,这是一个潜在的安全威胁。This example has a text box that accepts user input, which is a potential security threat. 默认情况下,ASP.NET 网页验证用户输入是否不包含脚本或 HTML 元素。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>

注解

ASP.NET 提供会话状态管理, 使你能够存储与跨多个请求的唯一浏览器会话关联的信息。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. 可以HttpSessionState使用类访问会话值和功能, 该类可Session通过当前HttpContext的属性或Session的属性Page进行访问。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. 默认情况下, 此标识符存储在浏览器中不过期的会话 cookie 中, 但你也可以将应用程序配置为在 URL 中存储会话标识符, 方法是cookieless将属性true设置UseUri为或在应用程序配置的 sessionState 元素。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. 可以通过将UseDeviceProfile cookieless属性的值指定为 ASP.NET 来确定浏览器是否支持 cookie。You can have ASP.NET determine whether cookies are supported by the browser by specifying a value of UseDeviceProfile for the cookieless attribute. 还可以让 ASP.NET 通过AutoDetect cookieless为属性指定值来确定是否为浏览器启用了 cookie。You can also have ASP.NET determine whether cookies are enabled for the browser by specifying a value of AutoDetect for the cookieless attribute. 如果在指定时支持UseDeviceProfile cookie, 或在指定时AutoDetect启用了, 则会话标识符将存储在 cookie 中; 否则, 会话标识符将存储在 URL 中。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.

会话将在第一次请求期间启动, 只要浏览器发出新请求, 就会保留在Timeout属性传递中指定的分钟数之前的会话值。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. 新会话开始时, 将引发会话Start事件。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. 当会话超时时, 将Abandon调用方法, 否则将会关闭 ASP.NET 应用程序。 EndWhen 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. 仅当会话状态mode设置为InProc时才引发事件。EndThe End event is raised only when the session state mode is set to InProc.

为了提高性能, 使用 cookie 的会话在数据实际存储在Session对象中之前不会分配会话存储。To improve performance, sessions that use cookies do not allocate session storage until data is actually stored in the Session object. 有关更多信息,请参见 SessionID 属性。For more information, see the SessionID property.

会话状态不会在 ASP.NET 应用程序边界之间保持。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.

默认情况下, 会话值存储在 Web 服务器的内存中。Session values are stored in memory on the Web server, by default. 你还可以在 SQL Server 数据库、ASP.NET 状态服务器或自定义服务器中存储会话值。You can also store session values in a SQL Server database, an ASP.NET state server, or a custom server. 这使您可以在 ASP.NET 或 IIS 进程或 ASP.NET 应用程序重启的情况下保留会话值并使会话值在 Web 场中的所有服务器上可用。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. 通过将mode属性设置为应用程序配置的sessionState元素中的有效值SessionStateMode来配置此行为。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.

会话状态的替代项包括应用程序状态 ( Application请参阅属性) 和 ASP.NET 缓存 ( System.Web.Caching请参阅命名空间), 该缓存存储可由 ASP.NET 应用程序的所有用户访问的变量; ASP.NET 配置文件 (请参阅System.Web.Profile命名空间), 它将用户值保留在数据存储中, 而不会使用超时值过期;ASP.NET System.Web.UI.WebControls, 它ViewState在中持久保存控制值;; 属性; 和 HTML 窗体上的字段, 可以使用Form集合通过 HTTP POST使用。 QueryString CookiesAlternatives 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. 有关会话状态与其他状态管理替代选项之间的差异的详细信息, 请参阅ASP.NET State Management 建议For more details on the differences between session state and other state-management alternatives, see ASP.NET State Management Recommendations.

属性

CodePage CodePage CodePage CodePage

获取或设置当前会话的字符集标识符。Gets or sets the character-set identifier for the current session.

Contents Contents Contents Contents

获取对当前会话状态对象的引用。Gets a reference to the current session-state object.

CookieMode CookieMode CookieMode CookieMode

获取一个值,该值指示是否为无 Cookie 会话配置应用程序。Gets a value that indicates whether the application is configured for cookieless sessions.

Count Count Count Count

获取会话状态集合中的项数。Gets the number of items in the session-state collection.

IsCookieless IsCookieless IsCookieless IsCookieless

获取一个值,该值指示会话 ID 是嵌入在 URL 中还是存储在 HTTP Cookie 中。Gets a value indicating whether the session ID is embedded in the URL or stored in an HTTP cookie.

IsNewSession IsNewSession IsNewSession IsNewSession

获取一个值,该值指示会话是否是与当前请求一起创建的。Gets a value indicating whether the session was created with the current request.

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

获取一个值,该值指示会话是否为只读。Gets a value indicating whether the session is read-only.

IsSynchronized IsSynchronized IsSynchronized IsSynchronized

获取一个值,该值指示对会话状态值的集合的访问是否是同步(线程安全)的。Gets a value indicating whether access to the collection of session-state values is synchronized (thread safe).

Item[Int32] Item[Int32] Item[Int32] Item[Int32]

按数字索引获取或设置会话值。Gets or sets a session value by numerical index.

Item[String] Item[String] Item[String] Item[String]

按名称获取或设置会话值。Gets or sets a session value by name.

Keys Keys Keys Keys

获取存储在会话状态集合中所有值的键的集合。Gets a collection of the keys for all values stored in the session-state collection.

LCID LCID LCID LCID

获取或设置当前会话的区域设置标识符 (LCID)。Gets or sets the locale identifier (LCID) of the current session.

Mode Mode Mode Mode

获取当前会话状态模式。Gets the current session-state mode.

SessionID SessionID SessionID SessionID

获取会话的唯一标识符。Gets the unique identifier for the session.

StaticObjects StaticObjects StaticObjects StaticObjects

获取由 ASP.NET 应用程序文件 Global.asax 中的 <object Runat="Server" Scope="Session"/> 标记声明的对象的集合。Gets a collection of objects declared by <object Runat="Server" Scope="Session"/> tags within the ASP.NET application file Global.asax.

SyncRoot SyncRoot SyncRoot SyncRoot

获取一个对象,该对象可用于同步对会话状态值的集合的访问。Gets an object that can be used to synchronize access to the collection of session-state values.

Timeout Timeout Timeout Timeout

获取或设置在会话状态提供程序终止会话之前各请求之间所允许的时间(以分钟为单位)。Gets or sets the amount of time, in minutes, allowed between requests before the session-state provider terminates the session.

方法

Abandon() Abandon() Abandon() Abandon()

取消当前会话。Cancels the current session.

Add(String, Object) Add(String, Object) Add(String, Object) Add(String, Object)

向会话状态集合添加一个新项。Adds a new item to the session-state collection.

Clear() Clear() Clear() Clear()

从会话状态集合中删除所有键和值。Removes all keys and values from the session-state collection.

CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32) 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) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

返回一个枚举数,可用来读取当前会话中所有会话状态的变量名称。Returns an enumerator that can be used to read all the session-state variable names in the current session.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
Remove(String) Remove(String) Remove(String) Remove(String)

删除会话状态集合中的项。Deletes an item from the session-state collection.

RemoveAll() RemoveAll() RemoveAll() RemoveAll()

从会话状态集合中删除所有键和值。Removes all keys and values from the session-state collection.

RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32)

删除会话状态集合中指定索引处的项。Deletes an item at a specified index from the session-state collection.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

扩展方法

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

适用于

另请参阅