Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to manage Session data

Tags:

c#

.net

asp.net

I need to persist in Session some data. I wrote many properties like that:

public List<string> FillOrder
{
    get { return Session[SessionKeys.QueryFillOrder] as List<string> ?? new List<string>(); }
    set { Session[SessionKeys.QueryFillOrder] = value; }
}

When I have to consume this data I have to write code like that:

List<string> fillOrder = FillOrder;
fillOrder.Add(accordion.ID);
FillOrder = fillOrder;

that seems to me so ugly, because I would prefer to do that:

FillOrder.Add(accordion.ID);

but this way my value would not be saved back in Session.

Can you think of any better way to achieve the same result?

Thank you very much!

like image 555
Alessandro Avatar asked Jan 19 '23 00:01

Alessandro


1 Answers

I always use a wrapper class around the ASP.NET session to simplify access to session variables:

public class MySession
{
    // private constructor
    private MySession()
    {
       FillOrder = new List<string>();
    }

    // Gets the current session.
    public static MySession Current
    {
      get
      {
        var session = (MySession)HttpContext.Current.Session["__MySession__"];
        if (session == null)
        {
          session = new MySession();
          HttpContext.Current.Session["__MySession__"] = session;
        }
        return session;
      }
    }

    // **** add your session properties here, e.g like this:
    public List<string> FillOrder {get; set; }
    public string Property1 { get; set; }
    public DateTime MyDate { get; set; }
    public int LoginId { get; set; }
}

This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:

MySession.Current.FillOrder.Add(accordion.ID);

int loginId = MySession.Current.LoginId;

string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;

DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;

This approach has several advantages:

  • you can initialize your session variables in the constructor (i.e. new List<string>)
  • it saves you from a lot of type-casting
  • you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]
  • you can document your session items by adding XML doc comments on the properties of MySession
like image 174
M4N Avatar answered Jan 22 '23 06:01

M4N