I want to use a session variable to store some data in my mvc 4 application but I'm a little unsure of the sessions life cycle. I have the timeout set and obviously it dies when that runs out but I'm curious as to what happens (and how I can control what happens) when:<ul><li>The browser closes</li> <li>Page is refreshed</li> <li>User logs out (I'm assuming I need to deal with this one manually)</li> </ul>Answer1:
I think aside from all the comments (which I think are all answers), the (other) key item to think about is that at the <em>client side</em> (browser), sessions are <em>cookies</em>. So if for example I set my browser to discard cookies each time I close it, that will "break" sessions.
Obviously, this doesn't apply to <em>cookieless sessions</em> (where the "identifier" is in the URL).
Also, look into <a href="https://stackoverflow.com/a/3737345/304683" rel="nofollow">this post</a> on <em>persistent</em> and <em>non-persistent</em> cookies (where a browser close, aka "browser session", will dump sessions).
<a href="http://msdn.microsoft.com/en-us/library/ms178194.ASPX" rel="nofollow">MSDN documentation</a>:<blockquote>
ASP.NET must track a session ID for each user so that it can map the user to session state information on the server. <strong>By default, ASP.NET uses a non-persistent cookie</strong> to store the session state. However, if a user has disabled cookies on the browser, session state information cannot be stored in a cookie.
ASP.NET offers an alternative in the form of cookieless sessions. You can configure your application to store session IDs not in a cookie, but in the URLs of pages in your site. If your application relies on session state, you might consider configuring it to use cookieless sessions. However, under some limited circumstances, <strong>if the user shares the URL with someone else—perhaps to send the URL to a colleague while the user's session is still active—then both users can end up sharing the same session</strong>, with unpredictable results.</blockquote>
That said, and depending on the type of data you want to <em>persist</em> for x time, you can also look into client side storage options (e.g. <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage" rel="nofollow"><em>web/dom/local storage</em></a>, etc.) in addition to/conjunction with or even perhaps a replacement to, <em>server/cookie based storage</em>. Note still, that this isn't "immune" to client/user action (user can dump all that data if/whenever they want to), nor any <strong>security</strong> implications.