共用方式為


HttpContext.Session 屬性

定義

取得目前 HTTP 要求的 HttpSessionState 物件。

public:
 property System::Web::SessionState::HttpSessionState ^ Session { System::Web::SessionState::HttpSessionState ^ get(); };
public System.Web.SessionState.HttpSessionState Session { get; }
member this.Session : System.Web.SessionState.HttpSessionState
Public ReadOnly Property Session As HttpSessionState

屬性值

目前 HTTP 要求的 HttpSessionState 物件。

範例

下列範例示範如何將值儲存在會話狀態,以及如何從會話狀態讀取值。

這些範例需要:

  • 已啟用工作階段狀態的 ASP.NET 應用程式。

  • 可存取 Page.Session 屬性的 Web Forms 頁面類別,或任何可存取屬性的 HttpContext.Current 類別。

string firstName = "Jeff";
string lastName = "Smith";
string city = "Seattle";

// Save to session state in a Web Forms page class.
Session["FirstName"] = firstName;
Session["LastName"] = lastName;
Session["City"] = city;

// Read from session state in a Web Forms page class.
firstName = (string)(Session["FirstName"]);
lastName = (string)(Session["LastName"]);
city = (string)(Session["City"]);

// Outside of Web Forms page class, use HttpContext.Current.
HttpContext context = HttpContext.Current;
context.Session["FirstName"] = firstName;
firstName = (string)(context.Session["FirstName"]);
Dim firstName As String = "Jeff"
Dim lastName As String = "Smith"
Dim city As String = "Seattle"

' Save to session state in a Web Forms page class.
Session("FirstName") = firstName
Session("LastName") = lastName
Session("City") = city

' Read from session state in a Web Forms page class.
firstName = DirectCast(Session("FirstName"), String)
lastName = DirectCast(Session("LastName"), String)
city = DirectCast(Session("City"), String)

' Outside of Web Forms page class, use HttpContext.Current.
Dim context As HttpContext = HttpContext.Current
context.Session("FirstName") = firstName
firstName = DirectCast(context.Session("FirstName"), String)

備註

屬性 Session 可讓您以程式設計方式存取 類別的屬性 HttpSessionState 和方法。

若要使用工作階段狀態,您必須加以啟用。 如需如何啟用會話狀態的資訊,請參閱在會話狀態概觀中設定會話狀態 ASP.NET

如需如何在會話狀態中儲存值的資訊,請參閱 如何:將值儲存在會話狀態。 如需如何從會話狀態讀取值的資訊,請參閱 如何:從會話狀態讀取值

適用於