Wednesday 2 March, 2011

Prevent Session Timeout in ASP.NET


What is an ASP.NET Session Timeout?

One of the biggest issues I've dealt with in ASP.NET over the years is session timeouts.  A session timeout occurs after a user is inactive for a set period of time.  The purpose of timeouts is to lock out unauthorized users when a system is unattended or when someone forgets to log out of an application. The only way to prevent a session from timing out is to keep activity between the browser and the server.  
For anyone who has edited web content or filled out a really long form has probably lost a significant amount of data to a session timeout.  In this article, I will tackle how-to prevent a session timeout in ASP.NET and when it is appropriate to use this method for keeping a session alive.

How-to prevent session timeout

To prevent our session from timing out, we simply need to maintain contact with the server.  
Step 1: Create a .NET web service
The web services doesn't really need to do anything, the call to the web service is enough to keep the session alive.
  1. [WebService(Namespace = "http://tempuri.org/")]
  2. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  3. [System.Web.Script.Services.ScriptService]
  4. public class webservice : System.Web.Services.WebService
  5. {
  6.     public webservice()
  7.     {
  8.     }
  9.      [WebMethod(Description = "Keeps your current session alive", EnableSession = true)]
  10.     public void PingSession()
  11.     {
  12.     }
  13. }
Step 2: Leverage ajax to call the web service
A simple call to the web service using jQuery.
  1. $(function() {
  2.     setInterval('pingSession()', 60000); // keep session alive by pinging every 60 sec
  3. });
  4. function pingSession() {
  5.     $.ajax({
  6.         url: '/services/webservice.asmx/PingSession',
  7.         data: {},
  8.         type: "POST",
  9.         processData: false,
  10.         contentType: "application/json; charset=utf-8",
  11.         timeout: 10000,
  12.         dataType: "text",
  13.         success: function(obj) {
  14.         }
  15.     });
  16. };

Usage

This method will prevent session timeout indefinitely, therefore, it should be used very conservatively.  I only recommend using it on pages that you risk losing valuable data that was entered.  For instance, if you are editing a large content in a WYSIWYG editor, you probably don't want the user losing an hours worth of work because of a session timeout.  The purpose of a timeout is to allow the server to free up memory that was allocated for a user.  If the session never ends, the memory is never free'd up.

No comments:

Post a Comment