Shopping Cart update quantities in database when user's session expires
I have a shop开发者_JS百科ping cart stored in session which decreases quantities of items stored in database when user clicks purchase.
If the user closes their browser before they have paid I want to return these quantities back into the database.
I am doing this in the void Session_End(object sender, EventArgs e) event in global.asax but the item quantities are not increasing. I set the session timeout to 1 minute in the web.config and the session is indeed ending because if i sit there with a full shopping cart, it is empty after a minute but the quantities in the database are not updated.
this is my code in session_end
void Session_End(object sender, EventArgs e)
{
if (ShoppingCart.Instance.Items.Count == 0)
return;
foreach (var cartItem in ShoppingCart.Instance.Items.OfType<CartItemGeneric>())
{
var stock = thisModel.EshopItems.Where(i => i.Id == cartItem.Item.Id).First();
stock.SapQuantity += cartItem.Quantity;
thisModel.SaveChanges();
}
}
Your problem is perhaps due the fact that session state may not available in the session end event. How do you reference the session state in ShoppingCart.Instance
accessor? Session end event is not necessarily fired while request in ending, so you may not have a valid HttpContext to get the session state.
Regardless, Session_End event is unreliable way to achieve what you want to do. For example, for out of process session, the event does not get raised. What will happen to your stock data if the app-domain hosting your web application crashes? The better solution is to mark your stock quantity only when the item is purchased (and not when item is added to the shopping cart).
精彩评论