Storing custom objects in Sessions

后端 未结 3 1106
遇见更好的自我
遇见更好的自我 2020-12-08 00:31

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, th

相关标签:
3条回答
  • 2020-12-08 01:14

    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.
    0 讨论(0)
  • 2020-12-08 01:24

    Generic Extension Method definition in a static class:

    public static T GetSession<T>(string key) =>  HttpContext.Current?.Session?[key] != null ? (T)HttpContext.Current.Session[key] : default(T);
    

    usage example implicit

    var myCart = GetSession<ShoppingCart>("myKey");
    

    inference

    ShoppingCart myCart2 = GetSession("myKey");
    

    check if exists

    if(myCart != default(ShoppingCart)){
        // do stuff
    }
    
    0 讨论(0)
  • 2020-12-08 01:26

    Add it to a master page or you could add a static property to you ShoppingCart object

    public static ShoppingCart GetCurrent
    {
        get
        {
            if(HTTPContext.Current.Session["CurrentCart"] == null)
            {
                HTTPContext.Current.Session["CurrentCart"] = new ShoppingCart();
            }
            return HTTPContext.Current.Session["CurrentCart"] as ShoppingCart;
        }
    }
    
    0 讨论(0)
提交回复
热议问题