I need a way to tell ASP.NET \"Kill the current session and start over with a brand new one\" before/after a redirect to a page.
Here\'s what I\'m trying to do:
The adding the cookie trick worked for me also, as follows:
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a new session is started
If Session.IsNewSession Then
'If Not IsNothing(Request.Headers("Cookie")) And Request.Headers("Cookie").IndexOf("ASP.NET_SessionId") >= 0 Then
If Not IsNothing(Request.Headers("Cookie")) AndAlso Request.Headers("Cookie").IndexOf("ASP.NET_SessionId") >= 0 Then
'VB code
Dim MyCookie As HttpCookie = New HttpCookie("ASP.NET_SessionId")
MyCookie.Expires = System.DateTime.Now.AddDays(-1)
Response.Cookies.Add(MyCookie)
'C# code
'HttpCookie mycookie = new HttpCookie("ASP.NET_SessionId");
'mycookie.Expires = DateTime.Now.AddDays(-1);
'Response.Cookies.Add(mycookie);
Response.Redirect("/timeout.aspx")
End If
End If
End Sub
The problem you are describing happens because asp.net is reusing the sessionid, if the sessionid still exists in the auth cookie when you call abandon() it will just reuse it, you need to explicitly create a new sessionid afaik something like:
HttpCookie mycookie = new HttpCookie("ASP.NET_SessionId");
mycookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(mycookie);
For ASP.NET MVC this is what I'm doing with an action method.
Note:
I return the current time and session id so you can verify the action completed succcessfully
public ActionResult ExpireSession()
{
string sessionId = Session.SessionID;
Session.Abandon();
return new ContentResult()
{
Content = "Session '" + sessionId + "' abandoned at " + DateTime.Now
};
}
Are you calling Session.Abandon in your special "Your session expired" page? If so, don't.
The code in your master page, which detects an expired session and redirects, should look like this:
if (Session != null
&& Session.IsNewSession
&& Request.Cookies["ASP.NET_SessionId"] != null
&& Request.Cookies["ASP.NET_SessionId"].Value != "")
{
Session.Clear();
Response.Redirect(timeoutPageUrl);
}
Calling session.Clear() before redirecting ensures that on the subsequent page, Session.IsNewSession will be false.
Also note that I am checking for an empty string in the value of of the ASP.NET_SessionId cookie. This helps to prevent a logout from being mistaken as an expired session, if you happen to call Session.Abandon() in your logout process. In that case, make sure you expire the old session cookie as a part of the logout process:
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.MinValue;