在 Sessions 中存储自定义对象 [英] Storing custom objects in Sessions

查看:28
本文介绍了在 Sessions 中存储自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在会话中存储自定义对象的一般方式是什么?

What the general way of storing custom objects in sessions?

我计划在整个 Web 应用程序的会话中保持我的购物车.当该用户退出时,会话将被清除.

I'm planning on keeping my cart in a session throughout the web application. When that user logs out, the session will be cleared.

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"]);
        }
    }
}

当用户登录时,我将购物车放入会话中,例如:

When the user signs in, I place the cart in a session, like:

Session["Cart"] = new ShoppingCart();

但是我必须在每一页上都写上 Session["Cart"] 吗?没有更简单的方法来做到这一点吗?访客购物车会话呢?我要在哪里声明?

But do I have to write Session["Cart"] on each and every page? Isn't there an easier way to do this? Also what about the Guest cart session? Where will I declare that?

我希望每个用户会话都存储在一个唯一的会话中,这样来宾会话和成员会话之间就不会混淆.

I want each user session stored in a unique session, so that there's no mixing up between the guest session and the member session.

推荐答案

ASP.NET 会话对应于浏览器会话 - 它与用户是否通过身份验证(登录)无关.因此,您不应该对来宾/会员会议有任何问题.我建议您通过静态访问器属性公开当前的购物车 - 例如

ASP.NET session corresponds to browser session - it is independent of whether user is authenticated (logged in) or not. So you should not have any issue with regards to guest/member sessions. I would advise you to expose the current shopping cart via static accessor property - for example

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

}

这里需要考虑的几件事:

Few things to consider here:

  1. 每当 Web 应用程序或 Web 服务器回收/重新启动时,您的进程内会话就会丢失.这意味着您需要在适当的时候将会话保存在数据库中.
  2. 您可以使用进程外会话存储(数据库或不同的服务器) - 在这种情况下,您必须将购物车类标记为可序列化.进程外会话存在性能成本.因此,您已经将会话存储在数据库中,因此 IMO,您应该使用进程内会话确保尽快将脏会话写入数据库.

这篇关于在 Sessions 中存储自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆