Detect when a session has ended ASP.NET

Posted by Tim on June 30, 2010 in .NET Framework, ASP.NET, Visual Basic |

A problem that I have had in the past is trying to find out when a session has expired within ASP.NET and how to deal with the expired session.   One solution is to add the following code into the Page_Init event.   You can add this event into a class that inherits the Page class so that you can reuse on more than one page or all pages if needed.

If Not Context.Session Is Nothing Then
If Session.IsNewSession Then
Dim szCookieHeader As String = Request.Headers("Cookie")
If Not String.IsNullOrEmpty(szCookieHeader) And szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0 Then
Response.Redirect("/sessiontimeoutpage.aspx")
End If
End If
End If

This code checks if a new session has been created and if the header has a ASP.NET Session id.   This makes sure that we are checking for a session that has just been created.

Tags: ,

1 Comment

Leave a Reply

Copyright © 2008-2010 Tim's CodeLab Blog All rights reserved.
Desk Mess Mirrored v1.7 theme from BuyNowShop.com.