Prevent Session Timeout in ASP.NET
Introduction
I have developed ASP and ASP.NET sites for many years and one of the most common end user problems is that while the user is entering information into a web form or HTML edit box, the session timeout period will elapse and they lose all the work they have done.
I have tried solutions such as making JavaScript alert the user to click a button or refresh page, but this has restrictions, especially if they are not able to submit the form yet due to required field limitations.
Solution
By using some code which attempted to fix this problem but that was unsuccessful because the author had forgotten the issue of client side caching.
Add to your page the following code:
private void Page_Load(object sender, System.EventArgs e)
{
this.AddKeepAlive();
}
private void AddKeepAlive()
{
int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000) - 30000;
string str_Script = @"
<script type='text/javascript'>
//Number of Reconnects
var count=0;
//Maximum reconnects setting
var max = 5;
function Reconnect(){
count++;
if (count < max)
{
window.status = 'Link to Server Refreshed ' + count.toString()+' time(s)' ;
var img = new Image(1,1);
img.src = 'Reconnect.aspx';
}
}
window.setInterval('Reconnect()',"+ _
int_MilliSecondsTimeOut.ToString()+ @"); //Set to length required
</script>
";
this.Page.RegisterClientScriptBlock("Reconnect", str_Script);
}
This code will cause the client to request within 30 seconds of the session timeout the page Reconnect.aspx.
The Important Part
Now this works the first time but if the page is cached locally then the request is not made to the server and the session times out again, so what we have to do is specify that the page Reconnect.aspx cannot be cached at the server or client.
This is done by creating the Reconnect.aspx page with this content:
<%@ OutputCache Location="None" VaryByParam="None" %>
<html>
</html>
The OutputCache
directive prevents this from being cached and so the request is made each time. No code behind file will be needed for this page so no @Page
directive is needed either.
And that's it.
Source :- Prevent Session Timeout in ASP.NET
No comments:
Post a Comment