skip to content
11 February 2008

Session Keep-Alive Web Control

Visual Studio project structure overview

Session expiration in ASP.NET is a nasty problem. Imagine yourself filling a long form, hitting submit then boom you get the login page! That happened to me before and probably happened to you.

This problem doesn’t have an out-of-box solution in ASP.NET and there are different appraoches to solve it.

  1. Increasing the session time out. Probably you are aware of the cons of this problem which are mainly consuming more server resources.
  2. Having an image or an iframe that refreshes regularly and requests the server. This approach is a per page approach and you can select the pages to implement it on.

Personally, I’ve been using the second approach for a long time and didn’t have any problem with it. However, I made it more reusable, not to mention “cleaner”, by making it a web control.

If you are just interested in using the control then you can skip to the last section “Using the Control.”


The architecture here is simple and consists of both server-side and client-side solutions.


An ASHX handler file hosted on the root of the site which when requested will renew the session and return a 1-pixel image. In my control, I called the ASXH file as session-keep-alive.ashx and this is the code:

<%@WebHandler Language="C#" Class="session_keep_alive"%>
using System.Web;
using System.Web.SessionState;

public class session_keep_alive : 
  IHttpHandler, IRequiresSessionState 
  private static byte[] gif = 

  public void ProcessRequest (HttpContext context)
    context.Response.ContentType = "image/gif";

  public bool IsReusable {
      return true;



On the client, my web control will render a 1-pixel image and some JavaScript code that will refresh the image every set amount of time from the ASXH file on the server. This is the control’s code:

using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.ComponentModel;

namespace AT.Web.UI.Controls 

/// <summary>
/// Web control to keep the session alive by refreshing 
/// every set amount of time
/// </summary>
    Level = AspNetHostingPermissionLevel.Minimal)]
    Level = AspNetHostingPermissionLevel.Minimal)]
[ToolboxData("<{0}:SessionKeepAlive runat=server />")]
public class SessionKeepAlive : WebControl {

/// <summary>
/// Set, in minutes, the duration to trigger the session.
/// The default value is one minute
/// </summary>
public int Duration {
    return (int)(ViewState["Duration"] ??  1);
    ViewState["Duration"] = value;

/// <summary>
/// The path of the image's URL that will be requested from the 
/// server, the default is ~/session-keep-alive.ashx
/// </summary>
public string PageUrl 
    return (string)(ViewState["PageUrl"] ?? "~/session-keep-alive.ashx");
    ViewState["PageUrl"] = value;

/// <summary>
/// Applies in-line CSS style to hide the generated image. 
/// The default is true. Alternatively, you can set this to false 
/// and hide the image using your own CSS to keep your page 
/// XHTML Strict compatible.
/// </summary>
public bool AutoHide
    return (bool)(ViewState["AutoHide"] ?? true);
    ViewState["AutoHide"] = value;

protected override void OnPreRender(EventArgs e) {

  if (AutoHide) 
    this.Style.Add(HtmlTextWriterStyle.Display, "none");


    typeof(SessionKeepAlive), "SessionKeepAlive",

    @"window.setInterval('SessionKeepAlive(\'{0}\', \'{1}\');', {2});",
    ClientID, ResolveClientUrl(PageUrl), Duration * 60000), true);

protected override void Render(HtmlTextWriter writer) 
    HtmlTextWriterAttribute.Src, ResolveClientUrl(PageUrl));
    writer.AddAttribute(HtmlTextWriterAttribute.Alt, " ");


And here is the used JavaScript, note that I am setting the Src of the image to
the same location (the ASHX file), but changing the query string to prevent the
browser from caching the request.

function SessionKeepAlive(imageID, pageUrl) 
  var imageObj = document.getElementById(imageID);
  if (imageObj == null || imageObj == undefined) 
  imageObj.src = pageUrl + "?par=" + 
          escape((new Date()).toString());

Using the JavaScript as an embedded resource

I have made the JavaScript file an embedded resource to make it easier for deployment. To do that I had to do the following:

  1. Added a javascript file to the project library and called it JavaScript.js
  2. I made this file an embedded resource by selecting it and setting Build Action to Embedded Resource
  3. I have added the following line to the AssemblyInfo.cs : [assembly: WebResource("AT.Web.UI.Controls.JavaScript.js","application/x-javascript")]

Using the Control

  1. Copy session-keep-alive.ashx to your website.
  2. Reference AT.Web.UI.Controls.dll in your website.
  3. You can add this control to the VS.NET toolbox and drop anywhere on the page OR you could add it manually by adding <%@ Register TagPrefix="at" Namespace="AT.Web.UI.Controls" Assembly="AT.Web.UI.Controls" %> to the top of the page and adding anywhere in the html body. You might need to set the refresh Duration, AutoHide or PageUrl

Check the sample file for more information.


The initial code that I used two years ago was based on an article, Make session last forever, written by Gevorg on Code Project.


This software is disributed under Ms-PL. Which simply means, you can freely use it and distribute it but you must retain all copyright, patent, trademark, and attribution notices that are present in the software.

Finally, if you like the article and find the control useful, then please Kick It (using the button below) and it would be kind of you to leave a comment. All suggestions and bug reports are welcome.

Download (19.55 kb)

leave your own
  • Rick February 24th, 2008

    Adam, when I try and add the Control from the Toolbox I get

    invalid formatetc structure

  • Adam Tibi February 26th, 2008


    The problem is solved, please try downloading the code again and let me know if it worked for you.


  • Thomas Hansen August 31st, 2008

    I did a session keep alive thing in Ra-Ajax using an Ajax Timer to poll the server every n’th minute while building a wiki system which is pretty easy. You just drag the Ra-Ajax Timer control onto the page, set its Milliseconds property to some fairly large value, and poff! It works πŸ™‚

  • Adam Tibi September 1st, 2008

    Yes, but that will require a whole AJAX framework, what you have called Ra-Aajx, before even thinking of implementing this.

    This is an easy solution which can fit in any ASP.NET 2.0 and above enviroment without additional requirments.

  • Rodger Cespedes October 22nd, 2008

    Thanks Adam Tibi, I really appreciate this work you have done and for sharing, it helped me a lot πŸ™‚

  • Amy November 13th, 2008

    Nice work! But I can’t make it work when dropping my usercontrol( that has your control on it) to a Master Page. Any suggestion for that?

  • Rob January 30th, 2009

    Hi Adam, I have tried to place the control on a masterpage, the page, in the update panel, outside of it and the session is lost after about 5 minutes. The handler is in the root (the vb version)/ In the web.config I have the timeout set for 5 minutes and slidingExpiration set to True. The application times out. Any suggestions?



  • Peter March 2nd, 2009


    Thanks for the control! Works as advertised πŸ™‚


  • Hai Nam June 21st, 2013


    It works. But when I add any more reference DLL then the Session times out.

    How can I keep the dll open from the beginning of the session to the end?

  • Adam Tibi June 21st, 2013

    @Hai Nam I am not sure I am getting your question. Could you elaborate more?

  • Hai Nam June 21st, 2013

    Oh, sorry Adam.
    My question is as follows :

    Your code works fine in my web app. Session is alive. But after I add some more DLL files as : ajaxcontroltoolkit.dll, System.Web.Extensions.dll … then Session expires in about 10 minutes.

    Can you help me with this problem ? Thanks.

  • Adam Tibi June 21st, 2013

    You might want to install a plugin for Firefox that shows JavaScript errors, you migh have a JS error.

Leave a Reply