Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

c# - Storing custom objects in Sessions

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. Whenever web application or web server recycles/restarts, your in-process sessions would lost. It means you need persist your session in database at appropriate point.
  2. You may use out of process session storage (database or different server) - you have to mark your shopping cart class as serializable in such case. There is performance cost to out-of-process sessions. As such, you are already storing session in database, so IMO, you should use in-proc sessions making sure to write dirty sessions into the database as soon as possible.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...