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

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

问题描述

在什么会议存储自定义对象的一般方式。
我打算让我的车在一个会话整个Web应用程序。当该用户注销,会话将被清除。

What the general way of storing custom objects in sessions. 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();

但我必须写会话[车]对每一个页面。是不是有更简单的方法来做到这一点?也对游客的购物车会是什么?我会在哪里声明?

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?

我要存储在一个唯一的会话每个用户会话。使那里有访客会话和成员会议之间没有mmixing了。

I want each user session stored in a unique session. So that theres no mmixing 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. 您可以使用进程外会话存储(数据库或不同的服务器)的 - 你必须标记你的购物车类在这种情况下为可序列化。有性能代价进程外的会话。因此,您已经存储的数据库会话,因此海事组织,你应该使用进程内会话并确保尽快脏会写入到数据库中。

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

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