Click here to Skip to main content
15,868,016 members
Articles / Web Development / ASP.NET
Article

The Defibrillator: Keeping ASP.NET Session Alive Ad Infinitum

Rate me:
Please Sign up or sign in to vote.
4.68/5 (60 votes)
31 May 20054 min read 363.6K   106   74
With only two lines of code (no joking) keep your session alive as long as the user stays on your site.

Introduction to the Defibrillator

Sometimes you want to keep a session alive only as long as the user is on the site, or until they close their browser. You don't have security requirements in this situation that would make this a bad idea. You just want to keep the session timeout down, but let it persist as long as people are on your site (not just posting back to the server). I'm not kidding you when I tell you that I have figured out a way to do this with two lines of code.

Coming from a biomedical engineering background, I simply had to call this construct The Defibrillator :-) You'll soon see why.

Nuts and Bolts

The most elegant engineering solutions are the simplest ones. You break down a problem into its finest components, and then focus on applying your vast knowledge to each component in order to produce a unified solution.

There are only four concepts to this solution:

  • Knowledge of the Response.
  • Knowledge of the Refresh HTTP header attribute.
  • Session property access.
  • Plain old IFrame.

You will create a dummy WebForm called Defibrillator.aspx. You do nothing with this page other than add one line on the Page_Load in the code behind file:

C#
private void Page_Load(object sender, System.EventArgs e)
{
    Response.AddHeader("Refresh", Convert.ToString((Session.Timeout*60)-10));
}

You just added the Refresh HTTP Header Attribute to the WebForm and gave it a value of your session timeout minus ten seconds. What does that mean? It means that ten seconds before the user's session is going to timeout, as long as they have a browser open, and they are on your page, this defibrillator page will deliver massive amounts of electrical current to your server, jolting the user's session back from the brink of death...which can also be described as automatically posting back to keep the session alive :-).

Great, you say...I don't want my site to post back visibly just to keep the session alive. You don't have to. This is where the second line of code comes in.

Go into your user control that is site persistent, such as the header, or footer user control. Now add this line of code into the front end WebForm markup language:

HTML
<IFRAME id=Defib src="/Defibrillator.aspx" 
     frameBorder=no width=0 height=0 runat="server"></IFRAME>

Now this invisible Defibrillator WebForm will just sit in the IFrame and post itself back to the server 10 seconds before the session times out, only if they are still on your site or a browser is open. Check out a View Source, you won't even see the Refresh attribute because it's hanging out in the invisible IFrame.

Please use this clever little trick with discretion and an understanding of your blade resources, or else I will have an army of network administrators ready to storm my fort :-)

Caveats

  • Browser Compatibility

    It will work in any browser that interprets the Refresh HTTP header. In Netscape it has the effect of hitting 'Reload' at the specified time. I have read online that this refresh will exclude your page from search engine crawling... which is fine since you put this functional tag on a dummy page in an IFrame, that you don't want anyone browsing to anyway.

  • Out of our control: precision of ASP.NET timeout on server.

    I've found that the session timeout itself in ASP.NET is not entirely accurate, especially when you are in a debug process. While I haven't had the Defibrillator fail for Session.Timeout - 10 seconds, I tested for 2 days with Session.Timeout - 5 seconds and it failed at around 36.5 hours of inactivity, because the ASP.NET session timed out before it was supposed to on the server. You may want to keep this in mind and perform your own little test. You could even fire up different browsers and let them rip, logging a time of failure and the browser type from the Request in your DB. So far so good on my app, no problems with the way I presented the solution here on Netscape or IE 6. (RE: Joe).

Extension

Write a combination of code in the defibrillator that works on a JavaScript timer, prompting the user to refresh session, and replace the Refresh HTTP header attribute with this construct. Since it is site persistent, put as much JavaScript into your .js files as possible. (RE: Fredrik)

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
Web Developer
United States United States
Broad engineering background, Virginia Tech Alum. Attracted to .NET by the sheer power of the framework and elegance of c#. Work includes analytical system to calculate joint torque during balance recovery to recommend physical therapy routines and correct bad biomechanics (preventative medicine). Assimilated force plate and 3D kinematic data for modeling. First and sole developer ever to fully automate corporate housing quotes, which I built into a larger engine that serves the company's entire enterprise.

Experience with applications architecture, DB design and UML 2.0. Experience with a broad range of applied mathematics, FEM software coding, solid and fluid mechanics. Great knowledge of healthcare and physiology with degree in Mechanical/Electrical/Materials Engineering Theory (Engineering Science and Mechanics) and concentration in biomechanics.

Currently expanding my corporate housing business engine by day. By night I am expanding my software engineering design and construction knowledge, staying in touch with the direction of healthcare management systems, and moving music business technology forward. Microsoft is now working on blowing iTunes out of the water, but my business is making an even bigger revolution that is far beyond just music retail. It strikes at the heart of the music industry's issues, and perhaps we will consider partnering with Microsoft to feed their music retail goals while they feed our music licensing, publishing, and digital decentralization of distribution.

I am the Enterprise Architect at my company and maintain a small but powerful and effective team. I have personally customized CxOne from construx (www.construx.com) for this team. Long live Steve McConnell.

Comments and Discussions

 
QuestionExcellent Solution!!! Pin
Emmanouil Gimissis MSc ICSD20-Jun-17 20:51
professionalEmmanouil Gimissis MSc ICSD20-Jun-17 20:51 
GeneralMy vote of 5 Pin
chetan virkar29-May-12 2:03
chetan virkar29-May-12 2:03 
GeneralLoad issuse Pin
PreethiSethuraman4-May-11 20:02
PreethiSethuraman4-May-11 20:02 
GeneralSuperb Idea Pin
Virat Kothari11-Nov-09 18:38
Virat Kothari11-Nov-09 18:38 
Questionwill it work if browser is minimized? Pin
Pete Levine27-Aug-09 12:28
Pete Levine27-Aug-09 12:28 
AnswerRe: will it work if browser is minimized? Pin
Pete Levine31-Aug-09 10:39
Pete Levine31-Aug-09 10:39 
GeneralRe: Results I have had Pin
Daffy91327-Aug-09 2:39
Daffy91327-Aug-09 2:39 
GeneralSession in asp.net(C#) Pin
kva88826-Aug-09 2:03
kva88826-Aug-09 2:03 
Generalworks when use sqlserver as backend. Pin
jimmimohanan7-Jun-09 23:32
jimmimohanan7-Jun-09 23:32 
GeneralAwesome Pin
tumitaa28-Nov-08 6:18
tumitaa28-Nov-08 6:18 
Generalclass library? possible Pin
dsmportal14-Nov-08 3:07
dsmportal14-Nov-08 3:07 
Questionhow about the db connection? Pin
dsmportal14-Nov-08 3:06
dsmportal14-Nov-08 3:06 
Questionurgent question about this way of keeping session alive Pin
ladypins23-Jul-08 8:05
ladypins23-Jul-08 8:05 
AnswerRe: urgent question about this way of keeping session alive Pin
Thomas Kurek23-Jul-08 9:04
Thomas Kurek23-Jul-08 9:04 
GeneralRe: urgent question about this way of keeping session alive Pin
ladypins26-Jul-08 4:25
ladypins26-Jul-08 4:25 
GeneralRe: urgent question about this way of keeping session alive Pin
Member 771691712-Apr-12 9:42
Member 771691712-Apr-12 9:42 
Questionsilly question Pin
ladypins9-Jul-08 6:48
ladypins9-Jul-08 6:48 
GeneralCool tips Pin
Eins Tsang8-Jul-08 22:15
Eins Tsang8-Jul-08 22:15 
GeneralRe: Cool tips Pin
Thomas Kurek23-Jul-08 9:05
Thomas Kurek23-Jul-08 9:05 
GeneralMaybe you would also like to check out Pin
swedishspeeder2-Sep-07 7:06
swedishspeeder2-Sep-07 7:06 
GeneralThanks, I really needed this solution. Pin
Buddy Stein1-Sep-07 4:17
Buddy Stein1-Sep-07 4:17 
GeneralRe: Thanks, I really needed this solution. Pin
Thomas Kurek1-Sep-07 5:23
Thomas Kurek1-Sep-07 5:23 
GeneralSimple and Worthy. Pin
Thiagarajan Rajendran10-Aug-07 8:59
Thiagarajan Rajendran10-Aug-07 8:59 
GeneralTime Out Issue Pin
naveenieus15-Jul-07 21:35
naveenieus15-Jul-07 21:35 
AnswerRe: Time Out Issue Pin
peter gabris12-Nov-07 7:32
peter gabris12-Nov-07 7:32 

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.