Generic Session Helper Class for ASP.NET MVC

I just wrote this. I haven’t tested it. I haven’t even run it. But surely it works, right!?!

What it is is a little helper class to allow you to get objects from the session in ASP.NET MVC (or, I assume, WebForms, though I don’t touch the stuff)

  1. namespace AwesomeWebApp.Helpers.Extensions
  2. {
  3.   using System;
  4.   using System.Web;
  5.  
  6.   public static class SessionExtensions
  7.   {
  8.     public static void AddItem<T>(this HttpSessionStateBase session, T item) where T : class
  9.     {
  10.       session[GetKey(item.GetType())] = item;
  11.     }
  12.  
  13.     public static T GetItem<T>(this HttpSessionStateBase session) where T : class
  14.     {
  15.       return session[GetKey(typeof(T))] as T;
  16.     }
  17.  
  18.     public static string GetKey(Type itemType)
  19.     {
  20.       return itemType.FullName;
  21.     }
  22.   }
  23. }

Pretty simple, no? You use it like this

  1. public ActionResult FirstAction()
  2.   {
  3.     var model = GetModelFromInput();
  4.     Session.AddItem(model);
  5.     return RedirectToAction("SecondAction");
  6.   }
  7.  
  8.   public ActionResult SecondAction()
  9.   {
  10.     var model = Session.GetItem<AwesomeModel>();
  11.     return View(model);
  12.   }

So, that’s it! I’m going to try to blog more smaller things like this. If this helped you, then do something nice for someone today! Or else I’ll hurt you. :)

Posted Friday, May 3rd, 2013 under ASP.NET MVC.

Leave a Reply