Keeping Your ASP.NET Session Alive Using jQuery

Posted by: Malcolm Sheridan , on 1/25/2010, in Category ASP.NET MVC
Views: 121618
Abstract: The following article demonstrates how to keep your session alive when you're using ASP.NET MVC and jQuery.
Keeping Your ASP.NET Session Alive Using jQuery
 
When you're working with the ASP.NET Session, it's important to remember that the session can timeout. The time before timing out is normally configured in the web.config file. Sometimes sessions time out at the most inconvenient time for your users. They could start a page, fill in some data, go to lunch then come back, click next and one of two things happen. Either the user is redirected back to the starting screen, or they'll get the ASP.NET yellow screen of death. That means the developer is not checking the session object for a null reference before using it. One workaround for this is to keep the users session alive by running a small snippet of code which updates a session object. I'll show you how to do this when you're building an ASP.NET MVC website.

 

The magic in this code lies in the JavaScript. To get a JavaScript function to run at intervals, you can use the setInterval function. This function runs a JavaScript function at set times. This means I can use jQuery's $.post method at set intervals to update one session object. That way it will keep the users session alive. I'm going to use an HttpHandler for this. These are perfect for this type of scenario as I don't want to create a separate controller or view for this.
To demonstrate this I’ve created an ASP.NET MVC application. The first thing you need to do is create the generic handler. I've added my handler and named it KeepSessionAlive.ashx. Here's the code for the handler:
C#
public class KeepSessionAlive : IHttpHandler, IRequiresSessionState
{
      public void ProcessRequest(HttpContext context)
      {
            context.Session["KeepSessionAlive"] = DateTime.Now;
      }
 
      public bool IsReusable
      {
            get
            {
                return false;
            }
      }
}
VB.NET (Converted Code)
Public Class KeepSessionAlive
      Implements IHttpHandler, IRequiresSessionState
      Public Sub ProcessRequest(ByVal context As HttpContext)
             context.Session("KeepSessionAlive") = DateTime.Now
      End Sub
 
       Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
             Get
                        Return False
             End Get
       End Property
End Class
Both of the methods above are mandatory when you inherit a class from the IHttpHandler interface. Notice in the code above I'm also inheriting IRequiresSessionState?
C#
public class KeepSessionAlive : IHttpHandler, IRequiresSessionState
If I didn't inherit my class from this interface, the ASP.NET Session wouldn't be available and a null reference exception would be thrown. When you inherit a class from IHttpHandler, the main method that you use is ProcessRequest. All this method is doing is touching one ASP.NET session object simply to keep the session alive.
Okay we've got our handler created, let's add some JavaScript to call this piece of code at set intervals. To do this I'm using the setInterval function. Here's the client side code:
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script language="javascript" type="text/javascript">
        $(function() {
            setInterval(KeepSessionAlive, 10000);
        });
 
        function KeepSessionAlive() {           
            $.post("/Shared/KeepSessionAlive.ashx", null, function() {
                $("#result").append("<p>Session is alive and kicking!<p/>");
            });   
        }   
    </script>
    <h2>Will my session die?</h2>   
    <div id="result"></div>
The code is simple but effective. When the page loads, I'm running setInterval to run my function every 10 seconds:
setInterval(KeepSessionAlive, 10000);
 
That function runs a jQuery post to the HttpHandler KeepSessionAlive.ashx:
 
$.post("/Shared/KeepSessionAlive.ashx", null, function() {
 
This means every 10 seconds the session will be updated behind the scenes. This will give the impression to the user that their session will not time out. Nice and simple.
 

For some websites it's mandatory to end sessions after a certain period of inactivity, but this is one way to keep your session alive if you want. The entire source code of this article can be downloaded over here

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Wayne on Monday, January 25, 2010 12:43 PM
Great stuff as usual :)
Comment posted by Sobin on Monday, January 25, 2010 1:15 PM
Hi Malcom,
Nice and simple article...
BTW,How can I achieve the same in the case of an ASP.NET website project?
Where do I put the javascript?in the masterpage?
Comment posted by Malcolm Sheridan on Monday, January 25, 2010 9:42 PM
@Wayne
Thanks!

@Sobin
The solution should be the same.  Just make sure your Http handler is in a folder called Shared, and then move your JavaScript into an aspx page.  
Comment posted by Sobin on Monday, January 25, 2010 10:13 PM
Hi Malcom,
Thanks for the quick reply.One more doubt..Placing the jscript in a single aspx page will keep the entire site's session alive?
ie, if I place the script in default1.aspx,and if the user is idle for a long time in default2.aspx,the session won't expire?
Comment posted by Malcolm Sheridan on Tuesday, January 26, 2010 12:54 AM
@Sobin
Sorry I thinking in terms of MVC again! Yes you're right. You'd need to move this code into a page that is vidible all the time, and normally that would be your master page.
Comment posted by Leon Chong on Tuesday, January 26, 2010 9:58 PM
Good stuff. Post more blogs like this.
Comment posted by Quintin on Wednesday, January 27, 2010 12:54 AM
Hi Malcom,
I have this scenario
i have a 2 pages, page1 and page2. Where page1 is inside a MasterPage and page2 is loaded in a div tag inside page1. If the user is iddle for a long time, will the session in page2 will not expire if i put the script inside the masterpage?
Looking forward for your reply. many thanks
Comment posted by Quintin on Wednesday, January 27, 2010 12:59 AM
Hi Malcom,
I have this scenario
i have a 2 pages, page1 and page2. Where page1 is inside a MasterPage and page2 is loaded in a div tag inside page1. If the user is iddle for a long time, will the session in page2 will not expire if i put the script inside the masterpage?
Looking forward for your reply. many thanks
Comment posted by Malcolm Sheridan on Wednesday, January 27, 2010 3:42 AM
@Quintin
The answer is it should keep your session alive.  When the pages are rendered, they're rendered as one page.
Comment posted by Quintin on Wednesday, January 27, 2010 7:23 PM
Thanks Malcom! I've created a test site and its working! We'll implement this in our site. This is great! Again, Thanks for this great article.
Comment posted by Malcolm Sheridan on Thursday, January 28, 2010 1:28 AM
@Quintin
Glad you liked it.  Thanks for the positive feedback!
Comment posted by Quintin on Friday, January 29, 2010 8:21 PM
Hi Malcom!
We made it working with our project. Locally hosted in my computer. But when we deploy it in the server, we found our the it is not working. here's the script

$(function(){
      setInterval(KeepSessionAlive, 60000);
});

function KeepSessionAlive(){            
      $.post("KeepSessionAlive.ashx", null, function(){
                var DateNow = new Date()
                window.status = "Last refresh " + DateNow;
      });    
}

other scripts work fine. Any idea?
Comment posted by Quintin on Friday, January 29, 2010 10:56 PM
Hi Malcom!

I tried adding this script $("#content").append("<p>Session is alive and kicking!<p/>"); and found out that its working.
But why is it the the window.status = "Last refresh " + DateNow; did not work. Any idea?

BTW, its working if i browse the site locally. It will not work only if i browsed it from different machines.

Thanks
Comment posted by Malcolm Sheridan on Sunday, January 31, 2010 5:19 AM
@Quintin
I'm not sure what's happening as when I try it locally it works.  If you find the issue let me know.
Comment posted by Google on Wednesday, February 17, 2010 5:37 AM
The answer is it should keep your session alive.  When the pages are rendered, they're rendered as one page.
Comment posted by jm on Wednesday, February 24, 2010 1:09 AM
If I knew you, I'd buy you a beer to celebrate your genius!  Thanks so much!
Comment posted by Oded on Wednesday, February 24, 2010 4:47 AM
fantastic explanation
Comment posted by Vince on Saturday, February 27, 2010 7:25 PM
Sorry, but this is not a solution to any problem. Timeout's are what free up memory on the server and are required for a healthy web application. This tell's me that your using session to store data about the users visit. A better approach would be to use a persistent medium such as a DB to store user prefs or whatever your storing.

Imagine users from all around the world 'pinging' your website to keep the session alive. It's a waste of server memory keeping everyone's session open and its also putting unnecessary strain on the server.

I wouldn't recomend this solution to anyone building a serious web application for use on a large scale. Intranet MAYBE.
Comment posted by Malcolm Sheridan on Tuesday, March 2, 2010 6:25 AM
@Vince
Not every website is as big as Twitter or Facebook.  Sometimes people want to keep the users session alive without the user moving away from the current page.  I do agree this is not for everyone, but it's an article that shows you, the reader, what is possible.
Comment posted by thomasvdb on Wednesday, March 17, 2010 10:02 AM
Nice article!

One (minor) problem though:
I always get a Javascript error regarding the ASHX file: "no element found".
Everything works fine but I'm wondering what's causing this error...
Comment posted by supriya on Thursday, March 25, 2010 5:27 AM
hi.
I have added the code for keeping the Session alive. When I run the site using ID it is working fine in both IE and firefox.But when I run it by placing the code in localhost then working fine in IE but not in firefox.
Could you please provide me the reason for not working in firefox.

Thanks.
Comment posted by supriya on Thursday, March 25, 2010 6:01 AM
hi.
I have added the code for keeping the Session alive. When I run the site using ID it is working fine in both IE and firefox.But when I run it by placing the code in localhost then working fine in IE but not in firefox.
Could you please provide me the reason for not working in firefox.

Thanks.
Comment posted by Ken on Friday, March 26, 2010 8:03 AM
Set your content lenght at 0. That fixed the problem for me.

public void ProcessRequest(HttpContext context)
{
      context.Session["KeepSessionAlive"] = DateTime.Now;
      context.Response.AddHeader("Content-Length","0");
}
Comment posted by thomasvdb on Tuesday, March 30, 2010 6:58 AM
@Ken: That did the trick! Thanks!
Comment posted by kazim on Wednesday, April 7, 2010 4:23 AM
nice idea and well presented
Comment posted by atagaew on Wednesday, April 7, 2010 5:59 AM
Thanks Man.
Really helpful trick.
Comment posted by Malcolm Sheridan on Saturday, April 10, 2010 4:58 AM
@Ken
Thanks for the tip.
Comment posted by Ray Akkanson on Thursday, July 8, 2010 12:17 PM
Using silverlight cache class can be a great solution to this problem.

Ray Akkanson
Comment posted by Ram T on Friday, July 9, 2010 9:50 AM
I am unable to open this project in VS.Net 2008. It says "The project type is not supported by this installation."
Comment posted by Dave on Saturday, July 17, 2010 12:48 AM
Great post - you saved the day!  This is a great alternative to setting the session timeout to 8 hrs or something ridiculous.
Comment posted by 9h0s7 on Saturday, August 7, 2010 4:45 PM
anyone getting the "implementing property must have matching 'readonly' or 'writeonly' specifiers" error change their code to look like this:
Implements IHttpHandler
    Implements IRequiresSessionState
    Public Sub ProcessRequest(ByVal context As HttpContext)
        context.Session("KeepSessionAlive") = DateTime.Now
    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

    Public Sub ProcessRequest1(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest

    End Sub
Comment posted by Carol on Monday, August 9, 2010 5:11 AM
Thanks 9h0s7. Our VB code is untested and converted using a tool. We have added the extra info in the original code for benefit of future readers.
Comment posted by Waqar Ahmad Bhatti on Wednesday, October 20, 2010 3:27 AM
http://waqarahmadbhatti.blogspot.com/2010/10/keeping-session-alive-in-aspnet.html
Comment posted by Zeeshan Umar on Monday, November 15, 2010 10:51 PM
Thanks for sharing, It is a nice trick to keep session alive. However what if application pool is restated?
Comment posted by Rajesh on Wednesday, December 22, 2010 5:35 AM
Hi Malcom,
Nice and simple article...I put the java script in the master page.It hits the handler page and successfully display "Session is alive and kicking".But on refresh of respective page,the session is getting expired.
Help me how to retain the session value which has been already defined in default.aspx...
Comment posted by Heinz on Monday, January 17, 2011 9:21 AM
Hi Malcolm,
I agree with Vince, Sessions should not be kept without reason. Wouldn't it be possible to combine this script with other user actions? For example if a user clicks on some buttons I want to refresh the session, but I don't want to do this just scheduled every 10 seconds.
Comment posted by Amit Seth on Wednesday, February 23, 2011 2:47 AM
If the intension is to just keep session alive we can simply define session timeout to expire after 5 years and this will never expire. Whats the purpose of writing handler?
Comment posted by WES on Wednesday, April 6, 2011 6:23 AM
NCache is an extremely fast in-memory distributed cache for .NET. NCache also provides an ASP.NET Session State storage that is reliable (thru replication) and scalable.
http://www.alachisoft.com/ncache/session_index.html
Comment posted by Javi on Monday, December 26, 2011 9:56 AM
I am using this solution but it´s not working. Do u think windows identity in IIS security is a problem?
Comment posted by ryan on Tuesday, January 24, 2012 12:59 PM
I am using this as well, but it's not keeping the session alive for me.
Comment posted by ryan on Tuesday, January 24, 2012 1:05 PM
I am using this as well, but it's not keeping the session alive for me.
Comment posted by Phil on Friday, June 15, 2012 5:16 AM
I'm thinking in terms of an intranet - but is this solution in a "shared" folder because it can be used by multiple websites on the same server? or should this .ashx file be include for each web project.
Comment posted by illusion on Thursday, June 21, 2012 10:20 AM
After reading the comments I realize that most of the commenters are not using the script for the disired reason.

It was made to keep session alive during INACTIVITY. Therefor, if your user is active and session still getting killed then this will not work for you. Look into cookies.
Comment posted by Khalid Mehmood on Wednesday, September 5, 2012 6:25 AM
This really helped me solving my problem and saved the day.
Comment posted by Aravinthan on Thursday, November 22, 2012 3:43 AM
Excellent article. u genious man.. Thank u so much i solved my session time out using this...
Comment posted by Blake on Friday, April 5, 2013 4:05 PM
Thanks very much for the idea.  
Comment posted by pstest on Friday, September 13, 2013 1:24 PM
We do not use either MVC / JQuery. I can apply JQuery.
Do you have example for ASP.Net without MVC?
Comment posted by pstest on Friday, September 13, 2013 1:44 PM
We do not use either MVC / JQuery. I can apply JQuery.
Do you have example for ASP.Net without MVC?
Comment posted by Zaid on Friday, October 4, 2013 6:18 AM
Please Brother Send me Code I am not using MVC and I could not find out the Code in SkyDrive

Regards
Zaid
Comment posted by Daniel Zhe on Wednesday, December 4, 2013 4:26 PM
Exactly what I was looking for.

Simple, clear and works very well.

Thank you!
Comment posted by Jep on Wednesday, February 12, 2014 8:18 PM
Hi I cant inherit IRequiresSessionState because it could not be found.
Comment posted by Ryan on Friday, February 14, 2014 11:39 PM
Very simple and nice. Thanks!
Comment posted by Roniu on Thursday, May 22, 2014 9:58 AM
Thanks. Simple and it works

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel