使用 Session 物件儲存值

System.Web.SessionState.HttpSessionState 物件提供了一種在 HTTP 請求之間保持值的方法。在下面的示例中,使用者對警告的首選項將儲存在會話中。稍後,在向使用者提供另一個請求時,應用程式可以從會話中讀取此首選項並隱藏警告。

public partial class Default : System.Web.UI.Page
{
    public void LoadPreferences(object sender, EventArgs args)
    {
        // ... 
        // ... A DB operation that loads the user's preferences.
        // ...

        // Store a value with the key showWarnings
        HttpContext.Current.Session["showWarnings"] = false;
    }

    public void button2Clicked(object sender, EventArgs args)
    {
        // While processing another request, access this value.
        bool showWarnings = (bool)HttpContext.Current.Session["showWarnings"];
        lblWarnings.Visible = false;
    }
}    

請注意,會話變數並非對所有使用者都是通用的(就像 cookie 一樣),並且它們在多個回發後保持不變。

會話通過設定包含使用者會話識別符號的 cookie 來工作。預設情況下,此識別符號與儲存在其中的值一起儲存在 Web 伺服器記憶體中。

以下是使用者瀏覽器中設定的 cookie 的螢幕截圖,用於跟蹤會話:

StackOverflow 文件