Click here to Skip to main content
15,892,072 members
Articles / Web Development / ASP.NET

Make session last forever

Rate me:
Please Sign up or sign in to vote.
4.24/5 (48 votes)
23 Oct 2006CPOL2 min read 175.8K   73   60
This article will show how to make the session last longer than 20 minutes of inactivity.

Introduction

You do not always have the luxury to bump up the session expiration period from 20 minutes on a server (most likely you are on a shared hosting). Plus it's a bad idea to unnecessarily consume the resources on a server. I have a simple solution that will take care of this problem.

Solution

The solution is simple. Let's create an ASPX page that will return a 1x1 transparent GIF image, and using JavaScript, refresh it every 15 minutes. Thus, the browser will renew the session every 15 minutes if the user is simply reading long text on a page or has walked away to get a cup of coffee. But if the browser is closed (or the user navigates away from our site), the session will expire after 20 minutes of inactivity. And we no longer consume the resources on the server.

Implementation

The implementation is rather simple, especially in the .NET environment.

  1. Create a renewSes.aspx page
  2. In the code-behind, add the following lines:
  3. C#
    public class renewSes : System.Web.UI.Page
    {
        static byte [] gif = {0x47,0x49,0x46,0x38,0x39,0x61,0x01,0x00,0x01,
                              0x00,0x91,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
                              0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x21,0xf9,
                              0x04,0x09,0x00,0x00,0x00,0x00,0x2c,0x00,0x00,
                              0x00,0x00,0x01,0x00,0x01,0x00,0x00,0x08,0x04,
                              0x00,0x01,0x04,0x04,0x00,0x3b,0x00};
    
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }
        
        private void InitializeComponent()
        {    
            Response.AddHeader("ContentType", "image/gif");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.BinaryWrite(gif);
            Response.End();
        }
    }

    This code will simply output a small 1x1 transparent GIF, which is in the array "gif", so we do not need to hit the file system for that. Plus, Cacheability is set to NoCache as we do not want the browser to hit the cache, but we want it to renew our session.

  4. Create a user control that has the following HTML:
  5. JavaScript
    <script language="Javascript">
    window.setInterval("renewSession();", 600000);
    function renewSession()
    {document.images("renewSession").src = "/renewSes.aspx?par=" + Math.random();}
    </script>
    <img src="/renewSes.aspx" name=renewSession id=renewSession>

    The code simply hits /renewSes.aspx every 10 minutes, thus keeping your session alive. Plus, Math.random was added to avoid caching in the browser.

  6. Dump it on every page somewhere. Or if you are using templates, then simply add it to your master page.
  7. Done!!! You might want to move the JavaScript code to RegisterClientScriptBlock, but it's not necessary.

Conclusion

Obviously, this method will only work if JavaScript is on, but it's a majority, plus do not forget that it's only for rare cases when the user leaves your page open and walks away expecting you will keep him logged in forever. The server resources are minimal since sessions will continue to expire every 20 minutes when the user navigates away, and the only excessive traffic is the 48 bytes every ten minutes to keep the session alive.

Sample

If you want to see how it works, feel free to visit my E-Commerce Body jewelry site. Add something to the shopping cart and wait for 20 minutes or for a couple days. When you will be back, the cart is still going to be there.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
I am a Senior Software developer who does a consulting work for several companies. Mostly it's an E-Commerce project.

I do have my own venture. Small online store my wife runs. Body Jewelry. Also visit Piercing info Cool thing is that nor I nor my wife has any piercings. My new website is Belly ring

Comments and Discussions

 
GeneralIts a good idea but here's a slight improvement Pin
Robert Ensor30-Jul-06 17:21
Robert Ensor30-Jul-06 17:21 
GeneralRe: Its a good idea but here's a slight improvement Pin
Gevorg31-Jul-06 4:38
Gevorg31-Jul-06 4:38 
AnswerRe: Its a good idea but here's a slight improvement Pin
Adam Tibi1-Aug-06 2:19
professionalAdam Tibi1-Aug-06 2:19 
GeneralRe: Its a good idea but here's a slight improvement Pin
Gevorg1-Aug-06 11:09
Gevorg1-Aug-06 11:09 
GeneralRe: Its a good idea but here's a slight improvement [modified] Pin
Robert Ensor1-Aug-06 11:53
Robert Ensor1-Aug-06 11:53 
AnswerRe: Its a good idea but here's a slight improvement Pin
Adam Tibi1-Aug-06 21:38
professionalAdam Tibi1-Aug-06 21:38 
QuestionWhat about db? Pin
ian.coetzer28-Jul-06 5:19
ian.coetzer28-Jul-06 5:19 
AnswerRe: What about db? Pin
Gevorg28-Jul-06 7:06
Gevorg28-Jul-06 7:06 
Are you saying that in your applications you do not use Session object?
Even if you are using Session that is kept in MS SQL i belive it is still going to expire in 20 minutes.

So you have your own Session managment procesdures for projects?
Affraid it's going to be overkill for majority of projects out there.

I would not argue with you that your approach is bulletproof but in reality i have yet to see an application that does it. (Never worked for yahoo,google, or amazon)



My site - Body Jewelry
Not my site - Piercing info

GeneralRe: What about db? Pin
ptmcomp1-Sep-06 9:46
ptmcomp1-Sep-06 9:46 
AnswerRe: What about db? Pin
JM_G23-Oct-06 21:49
JM_G23-Oct-06 21:49 
GeneralMy Girlfriends Pin
Varindir Rajesh Mahdihar27-Jul-06 10:36
Varindir Rajesh Mahdihar27-Jul-06 10:36 
GeneralRe: My Girlfriends Pin
Gevorg28-Jul-06 4:55
Gevorg28-Jul-06 4:55 
QuestionErr? Pin
Mark Cassidy18-Jul-06 22:11
Mark Cassidy18-Jul-06 22:11 
AnswerRe: Err? Pin
Gevorg20-Jul-06 11:16
Gevorg20-Jul-06 11:16 
GeneralRe: Err? Pin
Mark Cassidy20-Jul-06 21:20
Mark Cassidy20-Jul-06 21:20 
GeneralSuggestion Pin
Richard Deeming14-Jul-06 7:23
mveRichard Deeming14-Jul-06 7:23 
GeneralRe: Suggestion Pin
Gevorg14-Jul-06 7:39
Gevorg14-Jul-06 7:39 
GeneralRe: Suggestion Pin
sayedwasim14-Aug-06 20:26
sayedwasim14-Aug-06 20:26 
GeneralRe: Suggestion Pin
Richard Deeming15-Aug-06 0:24
mveRichard Deeming15-Aug-06 0:24 
GeneralSo Simple Pin
Boro_Bob13-Jul-06 23:09
Boro_Bob13-Jul-06 23:09 
GeneralScalability Pin
Mark Focas13-Jul-06 19:48
Mark Focas13-Jul-06 19:48 
GeneralRe: Scalability Pin
Gevorg14-Jul-06 7:28
Gevorg14-Jul-06 7:28 
GeneralRe: Scalability Pin
Brian.Brown27-Jul-06 10:40
Brian.Brown27-Jul-06 10:40 
AnswerRe: Scalability Pin
C# Genius29-Jul-06 9:27
C# Genius29-Jul-06 9:27 
GeneralRe: Scalability Pin
Gevorg1-Aug-06 10:57
Gevorg1-Aug-06 10:57 

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.