in .NET Framework

Detect when a session has ended ASP.NET

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.

1
2
3
4
5
6
7
8
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.