使用 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 文档