1

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:

  • The browser closes
  • Page is refreshed
  • User logs out (I'm assuming I need to deal with this one manually)
aw04
  • 10,857
  • 10
  • 56
  • 89
  • The session will survive all of them, in the second case the timeout starts with 0 again. – Tim Schmelter Feb 05 '14 at 13:38
  • What type of `SessionStateProvider` are you using? – Russ Cam Feb 05 '14 at 13:42
  • @TimSchmelter Thank you. So by setting it to a new instance when my app starts will the timeout restart each time as well? – aw04 Feb 05 '14 at 13:51
  • @aw04 If you don't know, chances are you are using the default `InProc` SessionStateProvider which will store session within the memory address space of the running application. When the Application Pool is recycled, Session will be lost – Russ Cam Feb 05 '14 at 14:05

1 Answers1

3

I think aside from all the comments (which I think are all answers), the (other) key item to think about is that at the client side (browser), sessions are cookies. 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 cookieless sessions (where the "identifier" is in the URL).

Also, look into this post on persistent and non-persistent cookies (where a browser close, aka "browser session", will dump sessions).

MSDN documentation:

ASP.NET must track a session ID for each user so that it can map the user to session state information on the server. By default, ASP.NET uses a non-persistent cookie 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, 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, with unpredictable results.

That said, and depending on the type of data you want to persist for x time, you can also look into client side storage options (e.g. web/dom/local storage, etc.) in addition to/conjunction with or even perhaps a replacement to, server/cookie based storage. Note still, that this isn't "immune" to client/user action (user can dump all that data if/whenever they want to), nor any security implications.

Community
  • 1
  • 1
EdSF
  • 11,753
  • 6
  • 42
  • 83