Click here to Skip to main content
Licence 
First Posted 31 May 2005
Views 181,784
Bookmarked 104 times

The Defibrillator: Keeping ASP.NET Session Alive Ad Infinitum

By | 31 May 2005 | Article
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:

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:

<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

About the Author

Thomas Kurek

Web Developer

United States United States

Member

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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 Pinmemberchetan virkar2:03 29 May '12  
GeneralLoad issuse PinmemberPreethiSethuraman20:02 4 May '11  
GeneralSuperb Idea PinmemberVirat Kothari18:38 11 Nov '09  
Questionwill it work if browser is minimized? PinmemberPete Levine12:28 27 Aug '09  
AnswerRe: will it work if browser is minimized? PinmemberPete Levine10:39 31 Aug '09  
GeneralRe: Results I have had PinmemberDaffy9132:39 27 Aug '09  
GeneralSession in asp.net(C#) Pinmemberkva8882:03 26 Aug '09  
Generalworks when use sqlserver as backend. Pinmemberjimmimohanan23:32 7 Jun '09  
GeneralAwesome Pinmembertumitaa6:18 28 Nov '08  
Generalclass library? possible Pinmemberdsmportal3:07 14 Nov '08  
Questionhow about the db connection? Pinmemberdsmportal3:06 14 Nov '08  
Questionurgent question about this way of keeping session alive Pinmemberladypins8:05 23 Jul '08  
AnswerRe: urgent question about this way of keeping session alive PinmemberThomas Kurek9:04 23 Jul '08  
Hi Ladypins, your concerns are valid. I'm sure by now there are more clever ways to make this happen, but before you implement this, I'd consider design first. Long ago, when I did this, my users truly could not store any data in cookies, and I had a State Server running so session state was fairly fast. These choices were satisfactory for my needs of the project at that time.
 
Consider what data you need to persist, and how it can be done, remember, you have: Application, Session State, View State, Control State, URLs, Cookies, Hidden Fields, RDBMS, Service Layer, etc. Search for MSDN State Persistence for more guidance. A good design will take you farther than thousands of hours of tinkering, trust me. In the case that you do actually need stress testing, check out Microsoft Visual Studio for Software Testers. It will give you an integrated suite of testing tools whereby you may simulate your anticipated operational load for your organization. Good luck, good thinking, and best wishes to you on your project! Please let me know what you decide to do to satisfy your state persistence requirements if you have the time.
 
Achieve by taking great pride in everything you're charged with, be successful by having the initiative to charge yourself, and realize that talent is comprised of aptitude, hard work, and spirit. Hone in on your aptitudes and dedicate your spirit to reach your full potential.

GeneralRe: urgent question about this way of keeping session alive Pinmemberladypins4:25 26 Jul '08  
GeneralRe: urgent question about this way of keeping session alive PinmemberMember 77169179:42 12 Apr '12  
Questionsilly question Pinmemberladypins6:48 9 Jul '08  
GeneralCool tips PinmemberEins Tsang22:15 8 Jul '08  
GeneralRe: Cool tips PinmemberThomas Kurek9:05 23 Jul '08  
GeneralMaybe you would also like to check out Pinmemberswedishspeeder7:06 2 Sep '07  
GeneralThanks, I really needed this solution. PinmemberBuddy Stein4:17 1 Sep '07  
GeneralRe: Thanks, I really needed this solution. PinmemberThomas Kurek5:23 1 Sep '07  
GeneralSimple and Worthy. PinmemberThiagarajan Rajendran8:59 10 Aug '07  
GeneralTime Out Issue Pinmembercoolnaveen123421:35 15 Jul '07  
AnswerRe: Time Out Issue Pinmemberpeter gabris7:32 12 Nov '07  
QuestionDoes this work with Master Pages? Pinmemberzoetosis22:57 22 May '07  

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

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120604.1 | Last Updated 31 May 2005
Article Copyright 2005 by Thomas Kurek
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid