我需要在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中.
你能想出更好的方法来达到同样的效果吗?
非常感谢你!
我总是在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>
)