Home > Asp.Net, JQuery > Keeping Your ASP.NET Session Alive Using jQuery

Keeping Your ASP.NET Session Alive Using jQuery

When we are working with Asp.Net,We should take care about Session 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,hat 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.

First we create a Generic Handler.Below is the code for Generic Handler(i.e. SessionAlive.ashx)

public class SessionAlive : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Session["KeepSessionAlive"] = DateTime.Now;
}

public bool IsReusable
{
get
{
return false;
}
}
}


public class KeepSessionAlive : IHttpHandler, IRequiresSessionState

If we didn’t inherit 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.

Now we write a javascript to call this SessionAlive.ashx code.For this we are using setInterval function.

Below is the Javascript Code

// <![CDATA[
javascript” type=”text/javascript” src=”http://code.jquery.com/jquery-latest.js”&gt;
// ]]>

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

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.

Advertisements
Categories: Asp.Net, JQuery
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: