Wednesday, 28 July 2010

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
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
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("

Session is alive and kicking!

");

});
}
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

No comments:

Post a Comment