Reputation: 43
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?
Upvotes: 3
Views: 2904
Reputation: 11
To remove the value from session in different ways
//Set the session variable
Session["User"]=Value;
//Destroy the session variable
Session.Remove("User");
Session["User"]=null;
// Abandon will destroy the session completely, meaning that you need to begin a new session before you can store any more values in the session for that user Session.Abandon(); //Clearing the session will not unset the session, it still exists with the same ID for the user but with the values simply cleared. Session.Clear();
Upvotes: 1
Reputation: 5909
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);
Upvotes: 6
Reputation: 11608
You should use:
Session.Clear();
Response.Redirect("Default.aspx");
Upvotes: 1