Click here to Skip to main content
15,879,184 members
Articles / Web Development / HTML
Article

Prevent Session Timeout in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.47/5 (57 votes)
16 Feb 20051 min read 693.9K   144   109
Simple code to prevent a sesison from timing out while a user enters data or edits HTML etc.

Introduction

I have developed ASP and ASP.NET sites for many years and one of the most common end user problems (apart from basic stupidity ;-) 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

I recently came across 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:

C#
private void Page_Load(object sender, System.EventArgs e)
{
this.AddKeepAlive();
}
C#
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:

ASP.NET
<%@ 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.

Hope this helps someone.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Founder Tech Dept
United Kingdom United Kingdom
My Evolution:
TRS-80 Basic, Clipper, C, Better Basic, FORTRAN, C++, Visual Basic, Delphi, C#

Comments and Discussions

 
GeneralRe: Please Help Pin
shetty7715-Jan-08 4:27
shetty7715-Jan-08 4:27 
QuestionThanks much, but what is redirect.aspx? Pin
Garry Freemyer30-Nov-07 12:17
Garry Freemyer30-Nov-07 12:17 
AnswerIt don't work for me. I'm stuck, They are demanding this! Pin
Garry Freemyer3-Dec-07 13:35
Garry Freemyer3-Dec-07 13:35 
GeneralRe: It don't work for me. I'm stuck, They are demanding this! Pin
Garry Freemyer7-Dec-07 11:09
Garry Freemyer7-Dec-07 11:09 
GeneralRe: It don't work for me. I'm stuck, They are demanding this! Pin
kannankeril17-Dec-09 11:19
kannankeril17-Dec-09 11:19 
QuestionPlease Help Pin
Dubey Yogendra16-Oct-07 4:42
Dubey Yogendra16-Oct-07 4:42 
AnswerRe: Please Help Pin
Ach1lles18-Oct-07 6:18
Ach1lles18-Oct-07 6:18 
GeneralThis is an alternative Pin
swedishspeeder2-Sep-07 7:01
swedishspeeder2-Sep-07 7:01 
just posted this as a reply to a question on forums.asp.net.

This alternative is a lot smoother if you use Ajax but works without is well.

You need to use a master page and sliding session expiration, or at least it's a lot easier that way. Of course you could jam a timer control in every page, but master pages are pretty nice for this and for other stuff as well. Well, in my master I page add:

<asp:timer id="tmCheckStatus" interval="1800000" runat="server">



Where the Interval (remember it's ms and not seconds) should be your session timeout minus at least 10 seconds. I prefer to go with 30 seconds to one minute before session expiration, depening on what I want to do when session is closing expiration. The 10 seconds is just because your session sometimes expires before the expiration you've set, butusually not ore than 10 seconds earlier. Do a little testing on this. Ok, now that I've got the timer control ticking, add a code behind to handle the tick of the timer. Protected Sub tmCheckStatus_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmCheckStatus.Tick
If b2bGlobal.isUserOnline = False Then
'This is if you use forms authentication
'but I'd say it works equally fine for 'normal' sessions
'Or you can fire a popup or redirect to a page asking the users
'if they want to stay online
FormsAuthentication.SignOut()
FormsAuthentication.RedirectToLoginPage()
End If
End SubWell, that's how I solve all annoying session timeouts and it's really easy. You can even set the timer interval to be (your session timeout value)/6 or some other number. For each tick you can change a picture or something like that, showing the ammount of time the user has left before automatic redirection occurs. It's nice for them and a cool feature for oneself, although one should take care not to let this sucker tick to much, as it could eat up server resources.


www.pixer.se
GeneralRe: This is an alternative Pin
AbbasHere26-May-08 18:19
AbbasHere26-May-08 18:19 
GeneralRe: This is an alternative Pin
rtitulaer2-Oct-08 5:29
rtitulaer2-Oct-08 5:29 
GeneralThanks Pin
Captain CAD29-Aug-07 8:51
Captain CAD29-Aug-07 8:51 
Generalyour solution so stupid Pin
Alireza Asgari6-Aug-07 6:58
Alireza Asgari6-Aug-07 6:58 
AnswerRe: your solution so stupid Pin
yogi6786-Aug-07 12:40
yogi6786-Aug-07 12:40 
GeneralRe: your solution so stupid Pin
Dewey12-Aug-07 11:26
Dewey12-Aug-07 11:26 
GeneralCool Pin
Hannes Foulds22-Jul-07 21:42
Hannes Foulds22-Jul-07 21:42 
GeneralThank you! Pin
Brian Duke20-Jul-07 5:07
Brian Duke20-Jul-07 5:07 
GeneralRe: Thank you! Pin
Jigs Shah14-Dec-08 20:43
Jigs Shah14-Dec-08 20:43 
GeneralRe: Thank you! Pin
Member 307583727-Mar-09 14:05
Member 307583727-Mar-09 14:05 
GeneralPrevent Session Timeout Pin
khanyile11-Jul-07 23:42
khanyile11-Jul-07 23:42 
GeneralRe: Prevent Session Timeout Pin
Ach1lles12-Jul-07 2:07
Ach1lles12-Jul-07 2:07 
GeneralVery Nice Pin
mBonafe22-May-07 3:55
mBonafe22-May-07 3:55 
GeneralMany Thanks Pin
Member 4089872-Mar-07 4:03
Member 4089872-Mar-07 4:03 
GeneralASP Version Pin
gregsta1-Mar-07 3:54
gregsta1-Mar-07 3:54 
GeneralRe: ASP Version Pin
rompi8-May-07 20:30
rompi8-May-07 20:30 
GeneralRe: ASP Version Pin
gregsta9-May-07 10:16
gregsta9-May-07 10:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.