Click here to Skip to main content
6,822,123 members and growing! (17,847 online)
Email Password   helpLost your password?
Web Development » Session State » Sessions and Session State     Intermediate

The Defibrillator: Keeping ASP.NET Session Alive Ad Infinitum

By Thomas Kurek

With only two lines of code (no joking) keep your session alive as long as the user stays on your site.
C#, Windows, .NETCF, .NET, Mobile, ASP.NET, Visual-Studio, WebForms, CEO, Architect, Dev
Posted:31 May 2005
Views:127,858
Bookmarked:92 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
53 votes for this article.
Popularity: 7.50 Rating: 4.35 out of 5
5 votes, 9.4%
1
2 votes, 3.8%
2
2 votes, 3.8%
3
11 votes, 20.8%
4
33 votes, 62.3%
5

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


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.
Occupation: Web Developer
Location: United States United States

Other popular Session State articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 70 (Total in Forum: 70) (Refresh)FirstPrevNext
GeneralSuperb Idea PinmemberVirat Kothari19:38 11 Nov '09  
Generalwill it work if browser is minimized? PinmemberPete Levine13:28 27 Aug '09  
GeneralRe: will it work if browser is minimized? PinmemberPete Levine11:39 31 Aug '09  
GeneralRe: Results I have had PinmemberDaffy9133:39 27 Aug '09  
GeneralSession in asp.net(C#) Pinmemberkva8883:03 26 Aug '09  
Generalworks when use sqlserver as backend. Pinmemberjimmimohanan0:32 8 Jun '09  
GeneralAwesome Pinmembertumitaa7:18 28 Nov '08  
Generalclass library? possible Pinmemberdsmportal4:07 14 Nov '08  
Generalhow about the db connection? Pinmemberdsmportal4:06 14 Nov '08  
Questionurgent question about this way of keeping session alive Pinmemberladypins9:05 23 Jul '08  
AnswerRe: urgent question about this way of keeping session alive PinmemberThomas Kurek10:04 23 Jul '08  
GeneralRe: urgent question about this way of keeping session alive Pinmemberladypins5:25 26 Jul '08  
Questionsilly question Pinmemberladypins7:48 9 Jul '08  
GeneralCool tips PinmemberEins Tsang23:15 8 Jul '08  
GeneralRe: Cool tips PinmemberThomas Kurek10:05 23 Jul '08  
GeneralMaybe you would also like to check out Pinmemberswedishspeeder8:06 2 Sep '07  
GeneralThanks, I really needed this solution. PinmemberBuddy Stein5:17 1 Sep '07  
GeneralRe: Thanks, I really needed this solution. PinmemberThomas Kurek6:23 1 Sep '07  
GeneralSimple and Worthy. PinmemberThiagarajan Rajendran9:59 10 Aug '07  
GeneralTime Out Issue Pinmembercoolnaveen123422:35 15 Jul '07  
AnswerRe: Time Out Issue Pinmemberpeter gabris8:32 12 Nov '07  
GeneralDoes this work with Master Pages? Pinmemberzoetosis23:57 22 May '07  
GeneralRe: Does this work with Master Pages? PinmemberThomas Kurek6:14 23 May '07  
GeneralRe: Does this work with Master Pages? Pinmemberzoetosis8:48 3 Jul '07  
GeneralWhat will happen if my page is processing some database operation? PinmemberJoshiMahesh20:44 8 Mar '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 31 May 2005
Editor: Smitha Vijayan
Copyright 2005 by Thomas Kurek
Everything else Copyright © CodeProject, 1999-2010
Web18 | Advertise on the Code Project