简体   繁体   中英

Better way to manage Session data

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!

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, eg 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 (ie 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 (eg Session["loginId"]
  • you can document your session items by adding XML doc comments on the properties of MySession

You can use an extension method as well, but I do think the example by M4N might be better:

EDIT made it a generic type

public static class Extensions
{
    public static void AddWithSession<T>(this List<T> list, T value, string key)
    {
        list.Add(value);
        HttpContext.Current.Session[key] = list;
    }
}

str.AddWithSession(accordion.ID,SessionKeys.QueryFillOrder);

您可以编写一个实现ICollection或IList的自己的类,在那里您将实现Add as Session [...] = ...

Using a single class for all Session variables as suggested by @M4N is a good idea, though it risks becoming a "God" class (in which case you could partition into several classes implemented in this way).

However you could just change your property implemetation as follows:

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

In this example, you probably don't want a setter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM