use*_*636 31 c# asp.net session
在会话中存储自定义对象的一般方法是什么.我打算在整个Web应用程序中保持我的购物车会话.当该用户注销时,会话将被清除.
Class ShoppingCart {
private List<CartItem> Items = new List<CartItem>();
public ShoppingCart()
{
this.Items = new List<CartItem>();
if (HttpCurrent.Current["Cart"]!=null])
{
this.Items = ShoppingCart.loadCart(HttpCurrent.Current["User"]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当用户登录时,我将购物车放在类似的会话中
Session["Cart"] = new ShoppingCart();
Run Code Online (Sandbox Code Playgroud)
但我是否必须在每一页上编写Session ["Cart"].有没有更简单的方法来做到这一点?还有Guest cart会话呢?我在哪里宣布?
我希望每个用户会话都存储在一个唯一的会话中.因此,在访客会话和成员会话之间没有任何混合.
Vin*_*ayC 39
ASP.NET会话对应于浏览器会话 - 它与用户是否经过身份验证(已登录)无关.所以你不应该对客人/会员会议有任何问题.我建议你通过静态访问器属性公开当前的购物车 - 例如
Class ShoppingCart {
public static ShoppingCart Current
{
get
{
var cart = HttpContext.Current.Session["Cart"] as ShoppingCart;
if (null == cart)
{
cart = new ShoppingCart();
HttpContext.Current.Session["Cart"] = cart;
}
return cart;
}
}
... // rest of the code
}
Run Code Online (Sandbox Code Playgroud)
这里很少考虑的事情:
将其添加到母版页,或者您可以将静态属性添加到 ShoppingCart 对象
public static ShoppingCart GetCurrent
{
get
{
if(HTTPContext.Current.Session["CurrentCart"] == null)
{
HTTPContext.Current.Session["CurrentCart"] = new ShoppingCart();
}
return HTTPContext.Current.Session["CurrentCart"] as ShoppingCart;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59829 次 |
| 最近记录: |