asp.netsessionsession-statesession-variables

strongly typed sessions in asp.net


Pardon me if this question has already been asked. HttpContext.Current.Session["key"] returns an object and we would have to cast it to that particular Type before we could use it. I was looking at various implementations of typed sessions

http://www.codeproject.com/KB/aspnet/typedsessionstate.aspx http://weblogs.asp.net/cstewart/archive/2008/01/09/strongly-typed-session-in-asp-net.aspx http://geekswithblogs.net/dlussier/archive/2007/12/24/117961.aspx

and I felt that we needed to add some more code (correct me if I was wrong) to the SessionManager if we wanted to add a new Type of object into session, either as a method or as a separate wrapper. I thought we could use generics

public static class SessionManager<T> where T:class
 {
  public void SetSession(string key,object objToStore)
  {
   HttpContext.Current.Session[key] = objToStore;
  }

  public T GetSession(string key)
  {
   return HttpContext.Current.Session[key] as T;
  }
    
 }

than using

HttpContext.Current.Session["sessionString"] as ClassType

SessionManager["sessionString"] = objToStoreInSession, but found that a static class cannot have an indexer. Is there any other way to achieve this ?

this would not work as well (as the return signature would be the same, but the return types will be different).

Is there any other elegant way of saving/retrieving objects in session in a more type safe way


Solution

  • For a very clean, maintainable, and slick way of dealing with Session, look at this post. You'll be surprised how simple it can be.