Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 Session.Abandon() called before setting a TempData["myvalue"] = "foo" causes the next controller to have TempData as null

I have a controller will logic that looks for a: Session value

 //checks value null etc..  for existing record in session memory.
 Session["certnum"]  

Then in the controller I had decided to have a condition where:

 //is called to initiate a New Record that will be created.
 Session.Abandon();

However In the procedural coding is that Session.Abandon(); comes before the creation of TempData["myobject"] = "foo" , and upon stepping through the code the TempData in immediate window shows my value and all seems good. Then upon redirect to another controller:

return RedirectToAction("ChildInfo", "NewRecord");  

This ChildInfo method no longer has the TempData value ... Now it is null. The Session Abandon Method was called way before the TempData value was set, not sure if this is a bug with MVC Sessions, but that make zero sense to me. If I am creating a new lighweight session TempData, then it should persist to the next controller. If I remove the Session.Abandon() method then the TempData value persist working as it did previously.

like image 815
Tom Stickel Avatar asked Sep 23 '11 22:09

Tom Stickel


2 Answers

The Session.Abandon() method clears the current session at the end of the request, that it what it is designed to do.

See http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.abandon.aspx

If you want to redirect to a different action, you do need to call the redirect like you have done. If you use Abandon() the request will get a new session id.

If you want to remove something from a session you need to use the Session.Remove or Session.RemoveAll methods (Also Clear can be used to do the same as RemoveAll. This would be done by:

Session.Remove(itemToRemove);

or

Session.RemoveAll()

By using either of these two options you can remove some or all previously stored data from the session without actually causing the session id to be regenerated on the next request.

like image 177
Bernie White Avatar answered Nov 15 '22 12:11

Bernie White


The Session.Abandon method doesn't clear the session object, it only flags that it should not be kept. The session object is still intact during the current request.

When the response is complete, the session object is abandoned, so that the next time the browser makes a request, the server has to set up a new session object. Anything that you put in the session object during that entire request goes away when the session object is abandoned.

When you make a redirect, a redirection page is sent as response to the browser, which then requests the new page. If you mark the session object to be abandoned and then do a redirect, the new page will get the new session object.

like image 25
Guffa Avatar answered Nov 15 '22 12:11

Guffa