In ASP.NET MVC 2, the lifespan of an entry in the TempDataDictionary
was just one HTTP Request.
That translated to setting a value in one request, redir
You're correct that TempData
keys are only cleared if they’ve been read (or after the user’s session expires) but this has been the case since MVC2, (http://forums.asp.net/post/3692286.aspx)
I'd like to know more about this implimentation change, what were the reasons for the change, was this simply to cater for multiple redirects or are there deeper benefits?
This change prevented problems that arose in MVC 1, such as TempData
keys being deleted before they were read. So yes, the primary benefit is in avoiding these problems when you have multiple re-directs, or interleaved requests. In addition, the RedirectToRouteResult
or RedirectResult
methods now automatically call TempData.Keep()
to prevent clearing of keys, even after they've been read so keep that in mind as well.
In scenarios where this is not the case such as wanting to read the TempData entry if redirected to one place, and expecting it to have been removed if requesting other resources and navigating back, this change has quite an impact.
You’re correct, if you've been coding under the assumption that the TempData
keys are cleared automatically you could run into unexpected problems. You can call TempData.Clear()
to manually remove all keys from the TempDataDictionary
, or TempData.Remove(key)
to remove a specific key. You can also use TempData.Peek()
to read the value of a TempData
key without flagging it for removal from the TempDataDictionary
.
Secondary to that, I'm intrigued to know if there's anything built in that now caters for single HTTP request sharing of data in the same way that TempData used to cater for?
I'm not aware of any new objects or functions that replicate the original implementation of TempData. Essentially we still use TempData
but have to be mindful that the data persists until read and clear the dictionary manually if needed.