Why would ASP.NET MVC use session state?

Ray picture Ray · Dec 22, 2008 · Viewed 48.8k times · Source

Recommended by the ASP.NET team to use cache instead of session, we stopped using session from working with the WebForm model the last few years. So we normally have the session turned off in the web.config

<sessionState mode="Off" />

But, now when I'm testing out a ASP.NET MVC application with this setting it throws an error in class SessionStateTempDataProvider inside the mvc framework, it asked me to turn on session state, I did and it worked. Looking at the source it uses session:

// line 20 in SessionStateTempDataProvider.cs
Dictionary<string, object> tempDataDictionary = 
httpContext.Session[TempDataSessionStateKey] as Dictionary<string, object>; 

So, why would they use session here? What am I missing?

========================================================

Edit Sorry didn't mean for this post to debate on session vs. cache, but rather in the context of the ASP.NET MVC, I was just wondering why session is used here. In this blog post also Scott Watermasysk mentioned that turning off session is a good practice, so I'm just wondering why I have to turn it on to use MVC from here on.

Answer

Craig Stuntz picture Craig Stuntz · Dec 22, 2008

Session is used for the TempData store. TempData is a highly limited form of session state which will last only until the next request from a certain user. (Edit In MVC 2+, it lasts until it is next read.) The purpose of TempData is to store data, then do a redirect, and have the stored data be available to the action to which you just redirected.

Using Session for the TempData store means that any distributed caching system which already handles Session will work for TempData. Avoiding using Session directly when TempData will do has a couple of advantages. One is that you don't have to clean up the Session yourself; TempData will "expire" on its own.