Introduction
Session timeout in ASP.NET is such an important problem with web developer. When session ends, we run into some exceptional situations. There are also many solutions to deal with this problem on the Internet. But few of them have discussed about redirecting to another page when there is session timeout, especially when we work with Ajax UpdatePanel
.
So, I suggest a way to do this.
Solution
My main idea is: 3 minutes before session is gone, we will alert the user to save his/her data or make any postbacks. If user still does not do anything, then 5 milliseconds before session goes, we will redirect the page to Login.aspx (or just refresh page by redirecting to itself).
Using the Code
Add the following code to your Master page:
private void CheckSessionTimeout()
{
string msgSession = 'Warning: Within next 3 minutes, if you do not do anything, '+
' our system will redirect to the login page. Please save changed data.';
int int_MilliSecondsTimeReminder = (this.Session.Timeout * 60000) - 3 * 60000;
int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000) - 5;
string str_Script = @"
var myTimeReminder, myTimeOut;
clearTimeout(myTimeReminder);
clearTimeout(myTimeOut); " +
"var sessionTimeReminder = " +
int_MilliSecondsTimeReminder.ToString() + "; " +
"var sessionTimeout = " + int_MilliSecondsTimeOut.ToString() + ";" +
"function doReminder(){ alert('" + msgSession + "'); }" +
"function doRedirect(){ window.location.href='login.aspx'; }" + @"
myTimeReminder=setTimeout('doReminder()', sessionTimeReminder);
myTimeOut=setTimeout('doRedirect()', sessionTimeout); ";
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
"CheckSessionOut", str_Script, true);
}
private void Page_Load(object sender, System.EventArgs e)
{
this.CheckSessionTimeout();
}
If you do not want to redirect to login page, you can just refresh the page by replacing it by this code:
function doRedirect(){ window.location.href=window.location.href; }
If you do not use ScriptManager, you can replace with Page.RegisterClientScriptBlock(...)
Hope this helps.
History
- 18th June, 2008: Initial post