HttpSessionState HttpSessionState HttpSessionState HttpSessionState Class

定義

提供工作階段狀態值以及工作階段層級設定和存留期 (Lifetime) 管理方法的存取權。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 Web 網頁會驗證使用者輸入未包含指令碼或 HTML 項目。By default, ASP.NET Web pages validate that user input does not include script or HTML elements. 如需詳細資訊,請參閱 Script Exploits Overview (指令碼攻擊概觀)。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屬性PageAccess 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屬性設定為trueUseUrisessionState應用程式組態項目。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. 您可以判斷是否 cookie 支援瀏覽器所指定的值為 ASP.NETUseDeviceProfile針對cookieless屬性。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 決定是否啟用 cookie 的瀏覽器所指定的值是AutoDetect針對cookieless屬性。You can also have ASP.NET determine whether cookies are enabled for the browser by specifying a value of AutoDetect for the cookieless attribute. 如果支援 cookie 時UseDeviceProfile已指定,或已啟用時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 應用程式關閉時,工作階段End就會引發事件。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. End就會引發事件時,才將工作階段狀態mode設定為InProcThe 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 屬性 (Property)。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屬性設為有效SessionStateMode中的值sessionState應用程式組態項目。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;Cookies;QueryString屬性,以及 HTML 表單上的欄位都是從 HTTPPOST使用Form集合。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. 如需工作階段狀態和其他狀態管理替代項目之間的差異的詳細資訊,請參閱 < ASP.NET 狀態管理建議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

取得值,指出對工作階段狀態值之集合的存取是否為同步的 (安全執行緒,Thread-Safe)。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 的淺層複本 (Shallow Copy)。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)

Extension Methods

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)

將轉換IEnumerableIQueryableConverts an IEnumerable to an IQueryable.

適用於

另請參閱