Session state in ASP.NET Core is significantly different to previous versions of ASP.NET, but it's not too complicated to work with:
Using Sessions and HttpContext in ASP.NET Core and MVC Core[
^]
List<Item> cart = HttpContext.Session.GetObjectFromJson<List<Item>>("AnansiCart") ?? new List<Item>();
cart.Add(...);
HttpContext.Session.SetObjectAsJson("AnansiCart", cart);
NB: Unlike previous versions of ASP.NET, updates to complex objects are not automatically stored. You'll need to call the
SetObjectAsJson
extension method after you've finished making your modifications.
For simplicity, you might want to declare a façade to encapsulate the session access:
public static class CartExtensions
{
private const string CartSessionKey = "AnansiCart";
public static List<Item> GetCart(this ISession session)
{
return session.GetObjectFromJson<List<Item>>(CartSessionKey) ?? new List<Item>();
}
public static void SaveCart(this ISession session, List<Item> cart)
{
session.SetObjectAsJson(CartSessionKey, cart);
}
}
That way, the key is only stored once, avoiding the possibility of typos, and you don't have to keep repeating the same code:
List<Item> cart = HttpContext.Session.GetCart();
cart.Add(...);
HttpContext.Session.SaveCart(cart);