back to Jitbit Blog home About this blog

ASP.NET Session: Caching Expiring Values

by Alex Yumashev · Apr 1 2011
Another post for ASP.NET/C# developers reading this blog. If you think these posts do not belong here, please leave a comment, and I'll consider moving my development articles to a separate blog.
Pretty often I need to cache something in the Session object, and expire the stored value after, say, 5 minutes. Just like it would in the ASP.NET Cache storage.

But the session state has no expiration concept. And the Cache object - well, cache is not specific to a user-session, it's application-wide. So I created this tiny useful extension class for this. Hope the code explains itself:

UPDATE: here's how you do it in 2017

OK, it is 2017 out there, the world has changed. Here's how you should do it these days (the code is pretty self-explanatory - you just add an async task that clean the value after a while). You can find the old code below (if you're still on .NET 3.5 or lower).


/// <summary>
/// this class saves something to the Session object
/// but with an EXPIRATION TIMEOUT
/// (just like the ASP.NET Cache)
/// (c) Jitbit 2011. License: MIT
/// usage sample:
///  Session.AddWithTimeout(
///   "key",
///   "value",
///   TimeSpan.FromMinutes(5));
/// </summary>

public static class SessionExtender
{
	public static void AddWithTimeout(this HttpSessionState session,
		string name,
		object value,
		TimeSpan expireAfter)
	{
		lock (session)
		{
			session[name] = value;
		}
		
		//add cleanup task that will run after "expire"
		Task.Delay(expireAfter).ContinueWith((task) => {
			lock (session)
			{
				session.Remove(name);
			}
		});
	}
}

Usage:

//store and expire after 5 minutes
Session.AddWithTimeout("key", "value", TimeSpan.FromMinutes(5));

//get the stored value just normally
var x = Session["key"];

The original way

/// <summary>
/// this class saves something to the Session object
/// but with an EXPIRATION TIMEOUT
/// (just like the ASP.NET Cache)
/// (c) Jitbit 2011. Feel free to use/modify/whatever
/// usage sample:
///  Session.AddWithTimeout(
///   "key",
///   "value",
///   TimeSpan.FromMinutes(5));
/// </summary>
public static class SessionExtender
{
  public static void AddWithTimeout(
    this HttpSessionState session,
    string name,
    object value,
    TimeSpan expireAfter)
  {
    session[name] = value;
    session[name + "ExpDate"] = DateTime.Now.Add(expireAfter);
  }

  public static object GetWithTimeout(
    this HttpSessionState session,
    string name)
  {
    object value = session[name];
    if (value == null) return null;

    DateTime? expDate = session[name + "ExpDate"] as DateTime?;
    if (expDate == null) return null;

    if (expDate < DateTime.Now)
    {
      session.Remove(name);
      session.Remove(name + "ExpDate");
      return null;
    }

    return value;
  }
}

Usage:

//store and expire after 5 minutes
Session.AddWithTimeout("key", "value", TimeSpan.FromMinutes(5));

//get the stored value
Session.GetWithTimeout("key");