Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a value from Session?

My session is not getting destroyed. This is how I set it up in Login.aspx.cs:

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

Link on the MasterPage:

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

The text in the link changes depending on whether the user has session or not:

    if (Session["User"] != null)
    {
        authspan.InnerHtml = "Logout";
    }
    else
    {
        authspan.InnerHtml = "Login";
    }

This link redirects to Login.aspx file in which on PageLoad I tell the code to close the session. In theory, this should work, right?

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.
    }

}

How can I end it for the logged in user correctly?

like image 264
hf185 Avatar asked Jan 17 '26 02:01

hf185


1 Answers

You must first clear session and then redirect.

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

Also note that, it is safer to remove session id on client side too:

    var sessionCookie = new HttpCookie("ASP.NET_SessionId");
    sessionCookie.Expires = DateTime.Now.AddDays(-1);
    Response.Cookies.Add(sessionCookie);
like image 75
Vano Maisuradze Avatar answered Jan 19 '26 17:01

Vano Maisuradze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!