I am trying to delete a list of products serialized as a Json object in a session but I am not sure how to go about it. Basically, I want to be able to delete a list of products once a user presses the cancels order button.
Here is where and how I initially set and serialized the session string and Json object respectively
public IActionResult OrderProduct(){
ProductViewModel productViewModel = new ProductViewModel();
return View(productViewModel);
}
[HTTPPost]
public IActionResult OrderProduct(ProductViewModel productViewModel){
Product product = new Product();
product.Id = productViewModel.Id;
List<Product> products = new List<Product>();
products.Add(product);
HttpContext.Session.SetString("SessionProducts", JsonConvert.SerializeObject(products));
returnToRedirect("ConfirmOrder");
}
[HTTPPost]
public IActionResult ConfirmOrder(){
var products= JsonConvert.DeserializeObject<List<Product>>(HttpContext.Session.GetString("SessionProducts"));
foreach(var product in products){
_productRepo.CreateOrder(product) //stores product in the database
}
return RedirectToAction("OrderSummary");
}
Once the user clicks the cancel order button, I have them redirected to this HTTPGET Action method below. Here, I was hoping to able to delete the session and the Json object so that the user can start all over to create a new order of products
public IActionResult UserMenu(){
if (HttpContext.Session.GetString("SessionProducts") != null){
/*
dynamic products= JsonConvert.DeserializeObject<List<Product>>(HttpContext.Session.GetString("SessionProducts"));
JObject jObject = JObject.Parse(products);
jObject.RemoveAll();
*/
HttpContext.Session.Remove("SessionProducts");
}
return View();
}
The problem is that HttpContext.Session.Remove("SessionProducts")
is not doing what I thought it would do (which is, to delete the session). I know this because when I try to persist the list of products in my database, it persists both the ones it was supposed to have deleted and the new add products. I now know that I HttpContext.Session.Remove("SessionProducts")
does not necessarily delete the session, but rather removes the key string. However, problem not is how can I delete both the session and the json object? How do I get this done the right way?