65.9K
CodeProject is changing. Read more.
Home

Detecting Session Timeout and Redirect to HomePage

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.88/5 (11 votes)

Sep 13, 2006

1 min read

viewsIcon

174104

downloadIcon

1721

Application that Detects when a Session has timed and redirect user to Home Page

Introduction

This application Detects when a Session has timmed and redirect user to the home page. Session Timeout can be changed in the Web.config file. Best to set this value to 1 (<sessionState ....timeout="1") to see quick effect. Unzip and Place projcet in the C:\Inetpub\wwwroot. Run Applcation and and click on the "MakeID" button followed by the "Page1" button. If session has not timed out Page1 should be displayed (click on the "Get ID" button to display the Session ID). If session has timed out a page saying "Session Time out" will be displayed (If user waites more than a minute)

Code: HomePage.aspx

The Code below created a session id when user click on the "Make ID" button.

    Private Sub bntMakeID_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bntMakeID.Click
        Dim session_id As Guid = Guid.NewGuid()
        Session(STATE_SESSIONID) = session_id.ToString
    End Sub
The Code below then calls "Page1.aspx" that will use the Session ID created in the code above. This code gets called when the "Page1" button is clicked
    Private Sub bntPage1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bntPage1.Click
        Response.Redirect("Page1.aspx")
    End Sub

Code: Page1.aspx

There are two ways for setting up this code to detect session time out

Step1: Inheriting from a Base Page

Base Calss is responsible for redirecting to Home Page

PageBase.aspx

The LoadBase function is called from the Page_Init
Public Class PageBase
    Inherits System.Web.UI.Page
..
..
    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
        LoadBase()
    End Sub
..
..

    Private Sub LoadBase()
        If Session("sessionID") = Nothing Then
            Response.Redirect("login.aspx")
        End If
    End Sub

End Class

Page1.aspx

Public Class Page1
     Inherits PageBase 

Step2: calling a local method

Page1.aspx calling method TestSessionStat

Page1.aspx

Note Page1 is no longer Inheriting from PageBase
Public Class Page1
    ' Inherits PageBase 
    Inherits System.Web.UI.Page

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
...
...
        TestSessionStat()
    End Sub

    Private Sub TestSessionStat()
        If Session("sessionID") Is Nothing Then 'sessionID
            Response.Redirect("login.aspx")
        End If
    End Sub