HttpSessionState 類別

定義

提供工作階段狀態值以及工作階段層級設定和存留期 (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
繼承
HttpSessionState
實作

範例

下列程式碼範例會設定並從會話狀態中抓取值。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 中,但您也可以設定應用程式,藉由在應用程式設定的 SessionState 專案中將此屬性設定為或,將會話識別碼儲存在 URL 中 cookieless true UseUriBy 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. 您可以讓 ASP.NET 藉由為屬性指定的值,判斷瀏覽器是否支援 cookie UseDeviceProfile cookielessYou 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 cookielessYou 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 ,或在指定時啟用 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.

會話會在第一個要求期間啟動,而且只要瀏覽器在屬性傳遞中指定的分鐘數之前提出新要求,就會保存會話值 TimeoutSessions 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 的會話不會配置會話儲存體,直到資料實際儲存在物件中為止 SessionTo 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 在應用程式設定的 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 ; Cookies ; QueryString 屬性; 以及 HTML 表單上的欄位,這些欄位可 POST 使用集合從 HTTP 取得 FormAlternatives 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

取得或設定目前工作階段的字集識別項。Gets or sets the character-set identifier for the current session.

Contents

取得目前工作階段物件的參考。Gets a reference to the current session-state object.

CookieMode

取得值,指出是否針對無 Cookie 工作階段設定應用程式。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

取得值,指出工作階段 ID 是否內嵌於 URL 或儲存於 HTTP Cookie。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

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

取得或設定目前工作階段的地區設定識別項 (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

取得由 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

取得物件,這個物件可以用來對工作階段狀態值集合進行同步存取。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.

方法

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.

(繼承來源 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.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 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.

(繼承來源 Object)

擴充方法

Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

啟用查詢的平行化作業。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryableConverts an IEnumerable to an IQueryable.

適用於

另請參閱