管理会话数据的更好方法

Ale*_*dro 4 .net c# asp.net

我需要在Session中保留一些数据.我写了很多这样的属性:

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

当我必须使用这些数据时,我必须编写这样的代码:

List<string> fillOrder = FillOrder;
fillOrder.Add(accordion.ID);
FillOrder = fillOrder;
Run Code Online (Sandbox Code Playgroud)

在我看来这么难看,因为我更愿意这样做:

FillOrder.Add(accordion.ID);
Run Code Online (Sandbox Code Playgroud)

但这样我的价值就不会保存在Session中.

你能想出更好的方法来达到同样的效果吗?

非常感谢你!

M4N*_*M4N 7

我总是在ASP.NET会话周围使用包装类来简化对会话变量的访问:

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; }
}
Run Code Online (Sandbox Code Playgroud)

此类在ASP.NET会话中存储自身的一个实例,并允许您以类型安全的方式从任何类访问会话属性,例如:

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;
Run Code Online (Sandbox Code Playgroud)

这种方法有几个优点:

  • 你可以在构造函数中初始化你的会话变量(即new List<string>)
  • 它可以帮助您避免大量的类型转换
  • 您不必在整个应用程序中使用硬编码会话密钥(例如Session ["loginId"]
  • 您可以通过在MySession的属性上添加XML doc注释来记录会话项