Click here to Skip to main content
15,885,216 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 694.6K   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

 
GeneralThere is a super simple way to handle this, about 8 lines of code and an iframe Pin
MTRIG18-May-11 10:03
MTRIG18-May-11 10:03 
Generallogin.aspx Pin
Ajay Kale New27-Sep-10 0:16
Ajay Kale New27-Sep-10 0:16 
Generalsession end Pin
Ajay Kale New9-Sep-10 4:17
Ajay Kale New9-Sep-10 4:17 
GeneralMy vote of 5 Pin
navneelb3-Aug-10 3:40
navneelb3-Aug-10 3:40 
QuestionNot working when run using IIS Pin
shyaz24-Jun-10 11:07
shyaz24-Jun-10 11:07 
GeneralIt can be done in multiple ways Pin
Eaverae1-Sep-09 22:31
Eaverae1-Sep-09 22:31 
Hi,

I develop a lot of asp.net websites, and I came across this issue also, especially in combination with the concept of url-rewriting. The way I re-write the url's is done through regular expressions, and because I disabled the session (to work around the time-outs), the url was rewritten like crap. The SessionID kept putting itself inbetween my urls, so I disabled the session altogether in web.config like so:<session mode="Off" />.

Then I rewrote my application to store all global (application) variables in a static class. Then we had the issue of logging in. So when logging in (which used to require SessionState in my application) I put the following code:

System.Web.Security.FormsAuthentication.SetAuthCookie(tbUSERNAME.Text, false);
Response.Redirect("~/Admin/Default.aspx");


And on top of the page which should be authenticated I put the following:

private string AuthenticatedUser = "";

        protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
                string temp = this.Page.User.Identity.Name;
                AuthenticatedUser = temp;
            }
            catch
            {

            }
            if (String.IsNullOrEmpty(AuthenticatedUser) == false)
            {
                //normal Page_Init code
            }
        }


Hope this is of any use to anyone. If you have questions, just ask!
GeneralGood Article... This is save my day... Pin
yogi230-Apr-09 17:10
yogi230-Apr-09 17:10 
Questionstop online banking time out Pin
jsmith0761124-Jan-09 22:14
jsmith0761124-Jan-09 22:14 
AnswerRe: stop online banking time out Pin
metweek5-Mar-09 17:28
metweek5-Mar-09 17:28 
GeneralASP.NET 2.0 Update w/AJAX Support Pin
Tim McCurdy28-Dec-08 14:26
Tim McCurdy28-Dec-08 14:26 
GeneralRe: ASP.NET 2.0 Update w/AJAX Support Pin
John Gleeson1-May-09 5:28
John Gleeson1-May-09 5:28 
GeneralRe: ASP.NET 2.0 Update w/AJAX Support Pin
Tim McCurdy1-May-09 10:57
Tim McCurdy1-May-09 10:57 
GeneralRe: ASP.NET 2.0 Update w/AJAX Support Pin
John Gleeson4-May-09 23:59
John Gleeson4-May-09 23:59 
QuestionRe: ASP.NET 2.0 Update w/AJAX Support Pin
thomasabcd2-Jun-09 0:12
thomasabcd2-Jun-09 0:12 
AnswerRe: ASP.NET 2.0 Update w/AJAX Support Pin
Tim McCurdy2-Jun-09 2:00
Tim McCurdy2-Jun-09 2:00 
GeneralRe: ASP.NET 2.0 Update w/AJAX Support Pin
thomasabcd2-Jun-09 4:13
thomasabcd2-Jun-09 4:13 
GeneralRe: ASP.NET 2.0 Update w/AJAX Support Pin
koger13-Sep-10 22:58
koger13-Sep-10 22:58 
GeneralRe: ASP.NET 2.0 Update w/AJAX Support Pin
Tim McCurdy14-Sep-10 2:57
Tim McCurdy14-Sep-10 2:57 
GeneralDisable caching Pin
rtitulaer2-Oct-08 5:33
rtitulaer2-Oct-08 5:33 
QuestionWhat about using an ajax call? Pin
Stuart Campbell13-Apr-08 18:54
Stuart Campbell13-Apr-08 18:54 
AnswerRe: What about using an ajax call? Pin
Jitu9914-Apr-08 6:41
Jitu9914-Apr-08 6:41 
GeneralRe: What about using an ajax call? Pin
Jorge Bay Gondra19-Sep-08 0:47
Jorge Bay Gondra19-Sep-08 0:47 
GeneralRe: What about using an ajax call? Pin
Member 307583727-Mar-09 14:02
Member 307583727-Mar-09 14:02 
AnswerRe: What about using an ajax call? Pin
johnlysam16-Jul-09 9:52
johnlysam16-Jul-09 9:52 
GeneralPlease Help Pin
shetty7714-Jan-08 4:06
shetty7714-Jan-08 4:06 

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.