Create new account I forgot my password    

Keeping Your ASP.NET Session Alive Using jQuery
Rating: 9 user(s) have rated this article Average rating: 4.6
Posted by: Malcolm Sheridan, on 1/25/2010, in category "ASP.NET MVC"
Views: this article has been read 27254 times
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

If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email

Malcolm Sheridan is an independent contractor who has been working with Microsoft technologies since VB4. Malcolm has worked with .NET since its inception and thoroughly enjoys ASP.NET.










Page copy protected against web site content infringement by Copyscape


How would you rate this article?

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 02, 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 07, 2010 4:23 AM
nice idea and well presented
Comment posted by atagaew on Wednesday, April 07, 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 08, 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 09, 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 07, 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 09, 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.

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

NEWSLETTER