如何从Session中删除一个值?

3

我的会话没有被销毁。这是我在Login.aspx.cs中设置的方式:

Session["User"] = UserName.Text; // Set the session called User.

主页上的链接:

<a href="Login.aspx" id="loginButton"><img src="images/login.png"><span runat="server" id="authspan">Login</span></a> 

链接中的文本会根据用户是否有会话而更改:
    if (Session["User"] != null)
    {
        authspan.InnerHtml = "Logout";
    }
    else
    {
        authspan.InnerHtml = "Login";
    }

这个链接将重定向到Login.aspx文件,其中在PageLoad事件中我告诉代码关闭会话。理论上,这应该有效,对吗?

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["User"] != null)
    {
        Response.Redirect("Default.aspx"); // Redirect user.
        Session["User"] = null; 
        Session.Remove("User"); 
    }
    else 
    {
        // run code that logs the user in, and sets up the session.
    }

}

如何正确地为已登录用户结束它?


2
你不是想要销毁会话,只是想从中删除一个值,对吗? - mason
抱歉,措辞不当。我还在学习中。 - hf185
4个回答

6

您必须先清除会话,然后再重定向。

    Session["User"] = null; 
    Session.Remove("User"); 
    Response.Redirect("Default.aspx"); // Redirect user.

另外需要注意的是,在客户端上删除会话 ID 更加安全:
    var sessionCookie = new HttpCookie("ASP.NET_SessionId");
    sessionCookie.Expires = DateTime.Now.AddDays(-1);
    Response.Cookies.Add(sessionCookie);

1
你应该使用:


Session.Clear();
Response.Redirect("Default.aspx");

1

有不同的方式可以从会话中删除值

//Set the session variable
Session["User"]=Value;
//Destroy the session variable
Session.Remove("User");
Session["User"]=null;

// Abandon会完全销毁会话,这意味着您需要在为该用户存储更多值之前开始一个新会话。 Session.Abandon(); //清除会话不会取消设置会话,它仍然存在于相同的ID下,但是值已被清除。 Session.Clear();


0
调用Session.Abandon();函数。(我必须写至少30个字符)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接