共用方式為


HttpSessionState 類別

定義

提供工作階段狀態值的存取,以及工作階段層級設定和存留期管理方法。

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
實作

範例

以下程式碼範例設定並擷取會話狀態的值。

這很重要

此範例中有一個文字框可接受使用者輸入,這可能構成安全威脅。 預設情況下,ASP.NET 網頁會驗證使用者輸入中不包含腳本或 HTML 元素。 欲了解更多資訊,請參閱 腳本漏洞概述

<%@ 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 提供會話狀態管理,讓你能在多個請求中儲存與獨特瀏覽器會話相關的資訊。 你可以儲存一組由鍵名或數值索引參考的值。 存取會話值與功能可透過 HttpSessionState 類別,該類別可透過 Session 當前 HttpContext的屬性或 Session 的屬性 Page存取。

會話資料會以唯一識別碼與特定瀏覽器會話相關聯。 預設情況下,這個識別碼會儲存在瀏覽器中的一個不會過期的會話 Cookie 中,但你也可以透過設定 cookielesstrueUseUri session State 元素的屬性來設定應用程式,將會話識別碼儲存在 URL 中。 你可以 ASP.NET 透過設定屬性的值UseDeviceProfilecookieless來判斷瀏覽器是否支援 Cookie。 你也可以讓 ASP.NET 透過屬性指定 的AutoDetectcookieless值來判斷瀏覽器是否啟用了 Cookie。 若 在指定時支援 UseDeviceProfile Cookie,或在指定時啟用 AutoDetect ,則會話識別碼會儲存在 Cookie 中;否則會話識別碼會儲存在 URL。

會話會在第一次請求時啟動,且只要瀏覽器在屬性指定的 Timeout 分鐘數前提出新請求,會話值就會持續存在。 當新會話開始時,會提出該會話 Start 事件。 你可以利用這個事件在工作階段開始時執行額外的工作,例如設定預設工作階段值。 當會話逾時、 Abandon 方法被呼叫,或 ASP.NET 應用程式關閉時,會話 End 事件被觸發。 你可以利用這個事件進行必要的清理。 只有當會話狀態mode被設定為 InProc時,事件End才會被觸發。

為了提升效能,使用 Cookie 的會話在資料實際儲存在物件中 Session 時才會分配會話儲存空間。 如需詳細資訊,請參閱 SessionID 屬性 (Property)。

會話狀態不會跨越 ASP.NET 應用程式邊界持續存在。 如果瀏覽器切換到另一個應用程式,該會話資訊將無法被新應用程式取得。

會話值預設儲存在網頁伺服器的記憶體中。 你也可以將會話值儲存在 SQL Server 資料庫、ASP.NET 狀態伺服器或自訂伺服器中。 這使你能在 ASP.NET 或 IIS 程序或 ASP.NET 應用程式重新啟動時保留會話值,並讓 Web 農場中所有伺服器都能使用。 此行為透過在應用程式設定的 sessionState 元素中設定mode屬性為有效SessionStateMode值來設定。 欲了解更多資訊,請參閱 Session-State 模式

會話狀態的替代方案包括應用程式狀態(見屬性Application)和 ASP.NET 快取(參見System.Web.Caching命名空間),它儲存了所有 ASP.NET 應用程式使用者都能存取的變數;ASP.NET 設定檔(參見System.Web.Profile命名空間),它能在資料儲存中持久保存使用者值而不使用逾時;ASP.NETSystem.Web.UI.WebControls,將控制值持續存在ViewState;CookiesQueryString;屬性;以及 HTML 表單中可從 HTTP POST 取得的欄位使用這個Form收藏。 欲了解更多關於會話狀態與其他狀態管理替代方案差異的細節,請參見 ASP.NET 狀態管理建議

屬性

名稱 Description
CodePage

取得或設定目前會話的字元集識別碼。

Contents

會取得目前 session-state 物件的參考。

CookieMode

會得到一個值,表示應用程式是否設定為無 Cookie 會話。

Count

取得會話狀態集合中的項目數量。

IsCookieless

會取得一個值,表示會話 ID 是嵌入在 URL 中,還是儲存在 HTTP cookie 中。

IsNewSession

會得到一個值,表示該會話是否是用目前的請求建立的。

IsReadOnly

會獲得一個值,表示該會話是否為唯讀。

IsSynchronized

會取得一個值,表示存取會話狀態集合是否同步(執行緒安全)。

Item[Int32]

透過數值索引取得或設定會話值。

Item[String]

透過名稱取得或設定會話值。

Keys

取得會話狀態集合中所有值的鍵集合。

LCID

取得或設定目前會話的區域識別碼(LCID)。

Mode

會取得目前的會話狀態模式。

SessionID

取得該會話的唯一識別碼。

StaticObjects

在 ASP.NET 應用程式檔案 Global.asax 中,透過標籤宣告 <object Runat="Server" Scope="Session"/> 的物件集合。

SyncRoot

取得一個物件,可用來同步存取會話狀態值集合。

Timeout

取得或設定請求間允許的時間(分鐘),直到會話狀態提供者終止會話。

方法

名稱 Description
Abandon()

取消當前的遊戲。

Add(String, Object)

新增一個項目到 session-state 集合中。

Clear()

移除會話狀態集合中的所有鍵與值。

CopyTo(Array, Int32)

將會話狀態的集合複製到一維陣列,從陣列中指定的索引開始。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetEnumerator()

回傳一個列舉子,可用來讀取目前會話中所有會話狀態變數名稱。

GetHashCode()

做為預設哈希函式。

(繼承來源 Object)
GetType()

取得目前實例的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
Remove(String)

從 session-state 集合中刪除一個項目。

RemoveAll()

移除會話狀態集合中的所有鍵與值。

RemoveAt(Int32)

從會話狀態集合中刪除指定索引的項目。

ToString()

傳回表示目前 物件的字串。

(繼承來源 Object)

擴充方法

名稱 Description
AsParallel(IEnumerable)

啟用查詢的平行處理。

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryable

Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。

OfType<TResult>(IEnumerable)

根據指定的型別篩選 IEnumerable 的專案。

適用於

另請參閱