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.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class webservice : System.Web.Services.WebService
{
public webservice()
{
}
[WebMethod(Description = "Keeps your current session alive", EnableSession = true)]
public void PingSession()
{
}
}
Step 2: Leverage ajax to call the web service
A simple call to the web service using jQuery.
$(function() {
setInterval('pingSession()', 60000); // keep session alive by pinging every 60 sec
});
function pingSession() {
$.ajax({
url: '/services/webservice.asmx/PingSession',
data: {},
type: "POST",
processData: false,
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "text",
success: function(obj) {
}
});
};
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