Reputation: 3424
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.
Upvotes: 33
Views: 74016
Reputation: 1673
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
}
Upvotes: 1
Reputation: 49195
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:
Upvotes: 43
Reputation: 1509
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;
}
}
Upvotes: 5