I am using the TempData
in order to preserve my model in when using a RedirectToAction
. It works fine, but I have a nagging feeling that it might not be the right thing to do. I really try to avoid using Session data, and I've read that TempData
uses the Session. Is it safe to use? Are there issues which might arise in using it in a load balanced environment?
Trivia Question: "Is It Safe?"-- name the movie.
TempData is able to keep data for the duration of a HTP request, in other words it can keep live data between two consecutive HTTP requests. It will help us to pass the state between action methods. TempData only works with the current and subsequent request. TempData uses a session variable to store the data.
TempData is ideal for short-lived things like displaying validation errors or other messages that we don't need to persist for longer than a single request. Session is ideal choice when we need to persist data for extended periods of time i.e. it is used to store data which is required throughout user session.
By default TempData uses the ASP.NET Session as storage. So it is stored on the server ( InProc is the default).
Yes, TempData is backed by session storage, so if you are in a load balanced environment extra care must be taken when using it (sticky sessions, persistent session state, etc).
TempData has been the de-facto choice when using the PRG pattern, and is what it was designed for.
As to whether it's the right thing to do... it depends on your use case!
PS Marathon Man.
Well, I would argue that it depends. If you handle lot of traffic with load balancers and multiple front end server, then session objects is something to avoid because it could degrade performance and make hotizontal scaling difficult (on farm request doesn't come always to same web server).
TempData is short-lived, and if you don't put there lot of objects there and think twice about whole architecture, I think then it's safe. There's lot of sites that use it extensively and don't have problems with it (I worked on shared and dedicated hosted sites with up to avarage 50-70k visitors/day that use session, often with web and db on same server).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With