我使用shoppingcart开发ASP.net 4.0应用程序。问题是用户1放置了一些东西,而用户2也得到了它。如何进行会话分享......
// Readonly properties can only be set in initialization or in a constructor
public static readonly ShoppingCart Instance;
// The static constructor is called as soon as the class is loaded into memory
static ShoppingCart() {
// If the cart is not in the session, create one and put it there
// Otherwise, get it from the session
if (HttpContext.Current.Session["ASPNETShoppingCart"] == null) {
Instance = new ShoppingCart();
Instance.Items = new List<CartItem>();
HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;
} else {
Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
}
}
请帮助,我找不到解决方案......
答案 0 :(得分:2)
不,不要使用这个静态变量:
public static readonly ShoppingCart Instance;
将其替换为:
public static ShoppingCart Instance
{
get
{
if (HttpContext.Current.Session["ASPNETShoppingCart"] == null) {
// we are creating a local variable and thus
// not interfering with other users sessions
ShoppingCart instance = new ShoppingCart();
instance.Items = new List<CartItem>();
HttpContext.Current.Session["ASPNETShoppingCart"] = instance;
return instance;
} else {
// we are returning the shopping cart for the given user
return (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
}
}
}