asna.com Sign In
How to tell if an ASP.NET session has timed out 

Download the AVR 8.0 example that uses the base page
Download the AVR 8.0 extended base page class library

Most AVR for .NET browser-based applications take maximum advantage of ASP.NET's Session object--and that object's in-process session variables. Session variables are used to store global application data that is unique to any one session. One of the challenges of effectively managing user sessions is gracefully with the occurrence of a session time. There are many tricks for do checking session. Often, these tricks include hard-coding a value with a given key and then checking that key value at page load time of all pages. If the value doesn't exist, the session has timed out.

This way works, but it's pretty hardcoded and makes you do special-case work for every page. Maybe there is a better way. First, let's explore a good way to generally determine if a session has expired. Thanks to Google, there isn't much thinking we need to do here. A Mr. Robert Boedigheimer has already solved the base problem! See Robert's very good article about how to determine if a session has timed out.

Bob's article uses a simple, application independent technique to determine if a session has timed out: he uses a combination of

  • checking to see if there is a session in play
  • checking to see if it is a new session
  • and checking to see if there is a session cookie in play
When these conditions are met, you know the session has timed out.

Bob's code, translated to AVR, is shown below:

    BegFunc IsSessionExpired Type( *Boolean ) Access( *Protected ) 
        DclFld CookieHeader Type( *String ) 
        DclFld Expired      Type( *Boolean ) Inz( *False )
        
        If ( Context.Session <> *Nothing ) 
            If ( Session.IsNewSession ) 
                CookieHeader = Request.Headers[ "Cookie" ]
                If ( CookieHeader <> *Nothing ) AND 
                           ( CookieHeader.IndexOf( "ASP.NET_SessionId" ) > -1 ) Expired = *True EndIf EndIf EndIf LeaveSr Expired EndFunc

To use this code, call the IsSessionExpired function from any page's Init event handler. If the function returns trues, the session has timed out and you can redirect the user to an information page about the session timing out.

    BegSr Page_Init Access(*Private) Event(*This.Init)
        DclSrParm sender Type(*Object)
        DclSrParm e Type(System.EventArgs)
        
        If ( IsSessionExpired() ) 
            Response.Redirect( "sessionExpiredPage.aspx" ) 
        EndIf 
    EndSr  

Important point!

Do note that ASP.NET doesn't actually create a session until you put something in the session. If you test the IsSessionExpired routine with a Web app that doesn't have a current session (because you haven't yet stored anything in a session variable), the function will always return false.

Improving the technique

As it is, this is a good technique, but let's make it better. Let's create our own enhanced version of ASP.NET's System.Web.UI.Page object and add testing to it for an expired session. To create the extended base page, start a new Class Library project. Name the project WebBasePages. Using the Solution Explorer, set a reference to the System.Web assembly (this makes the System.Web.UI.Page class available to use as the base class for extended page).

Add a SessionExpiredPage class with the code below. Note that this class extends from System.Web.UI.Page (as shown in yellow below) and checks for the session timeout in its Init event handler. To make things handy for consumers of this extended base page, this page raises the SessionExpired event when the session has expired.

Using System
Using System.Text

DclNamespace WebBasePages

BegClass SessionExpiredPage Access(*Public) Extends( System.Web.UI.Page ) 

    DclEvent SessionExpired Type( System.EventHandler ) 

    BegSr Page_Init Access(*Private) Event(*This.Init)
        DclSrParm sender Type(*Object)
        DclSrParm e Type(System.EventArgs)
        
        If ( IsSessionExpired() ) 
            SessionExpired( *This, *New System.EventArgs() )   
        EndIf 
    EndSr  

    BegFunc IsSessionExpired Type( *Boolean ) Access( *Protected ) 
        DclFld CookieHeader Type( *String ) 
        DclFld Expired      Type( *Boolean ) Inz( *False )
        
        If ( Context.Session <> *Nothing ) 
            If ( Session.IsNewSession ) 
                CookieHeader = Request.Headers[ "Cookie" ]
                If ( CookieHeader <> *Nothing ) AND 
                           ( CookieHeader.IndexOf( "ASP.NET_SessionId" ) > -1 ) Expired = *True EndIf EndIf EndIf LeaveSr Expired EndFunc EndClass

Compile the project and close the solution. To test your extended base page, start a new Web app. Add a reference to your BaseWebPages.DLL from the previous step. Also add the following three pages to it.

Default.aspx

Add this code to the page's Load event handler to ensure that a session gets started.

    BegSr Page_Load Access(*Private) Event(*This.Load)
        DclSrParm sender Type(*Object)
        DclSrParm e Type(System.EventArgs)

        If (NOT Page.IsPostBack)
            // Put something in a session variable to start a session.
            Session[ "x" ] = "x" 
        EndIf
    EndSr

Add a button to Default.aspx and its Click event, add this code
    Response.Redirect( "TestTimeOut.aspx" ) 

TestTimeOut.aspx

Note that this page extends WebBasePages.SessionExpiredPage (shown in yellow below), the class you created above. For testing purposes, the only code this page needs is to handle the SessionExpired event raised by the new extended base page. When that event is raised, you'll generally direct the user to a paging indicating what has happened.

// Using statements omitted for clarity

BegClass TestTimeOut Partial(*Yes) Access(*Public) Extends( WebBasePages.SessionExpiredPage )

    BegSr SessionExpired Access( *Private ) Event( *This.SessionExpired ) 
        DclSrParm sender Type(*Object)
        DclSrParm e Type(System.EventArgs)

        Response.Redirect( "SessionTimedOut.aspx" )     
    EndSr

EndClass

SessionTimedOut.aspx

For testing, this page doesn't need any code. It's just a target page to prove you can get to a special-case page when the session has timed out.

Setting the session time out value

By default, sessions timeout in 20 minutes. Add the following line to your application's Web.Config to change this value where x is the minutes to wait before a session times out. (Put this line immediately after the <system.web> line.)

    <sessionState mode="InProc" timeout="x" />

To test your project, set Default.aspx as the start page and run the app from inside Visual Studio. Wait about 30 seconds longer than your session timeout value (just to be sure) and click the button on Default.aspx to redirect to TestTimeOut.aspx. The SessionExpired event will fire and the user is sent directly to your session time-out page.

You could, if you wanted to, not even have your extended base fire an event and simply redirect to the session timeout page directly. By doing this, you'd not have to write any code for all of the pages in your application (that extend from WebBasePages.SessionExpiredPage) to test for session timeout. For example, assuming you had the convention that your apps always redirect to SessionTimedOut.aspx, you could simply use this code in your extended base page and not worry about raising the event:

    BegFunc IsSessionExpired Type( *Boolean ) Access( *Protected ) 
        DclFld CookieHeader Type( *String ) 
        DclFld Expired      Type( *Boolean ) Inz( *False )
        
        If ( Context.Session <> *Nothing ) 
            If ( Session.IsNewSession ) 
                CookieHeader = Request.Headers[ "Cookie" ]
                If ( CookieHeader <> *Nothing ) AND
                            ( CookieHeader.IndexOf( "ASP.NET_SessionId" ) > -1 ) Response.Redirect( "SessionTimedOut.aspx" ) EndIf EndIf EndIf LeaveSr Expired EndFunc

This article showed how to test, in an application independent-way (that is, no special-case session variables are required for it to work) for ASP.NET session time-out. Then, it built on that technique by introducting you to the concept of building your own base pages that provide general-purpose, frequently used code.
Related Articles
Article Downloads
 
Keywords:
 
Article ID: 397 
Category: ASNA Visual RPG : Web Development 
Applies To:  
Article Date: 1/1/2007