ASP.NET Session: Caching Expiring Values 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:

/// <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;
  }
}

0 comments:

Post a Comment



Blog Archive