2 // System.Web.SessionState.SessionInProcHandler
5 // Stefan Görling (stefan@gorling.se)
7 // (C) 2003 Stefan Görling
11 This is a rather lazy implementation, but it does the trick for me.
14 * Remove abandoned sessions., preferably by a worker thread sleeping most of the time.
15 * Increase session security, for example by using UserAgent i hashcode.
16 * Generate SessionID:s in a good (more random) way.
19 using System.Collections;
21 namespace System.Web.SessionState
23 // Container object, containing the current session state and when it was last accessed.
24 internal class SessionContainer
26 private HttpSessionState _state;
27 private DateTime last_access;
29 public SessionContainer (HttpSessionState state)
37 last_access = DateTime.Now;
40 public HttpSessionState SessionState {
42 //Check if we should abandon it.
43 if (_state != null && last_access.AddMinutes (_state.Timeout) < DateTime.Now)
56 internal class SessionInProcHandler : ISessionHandler
58 protected Hashtable _sessionTable;
59 const string COOKIE_NAME = "ASPSESSION"; // The name of the cookie.
60 // The length of a session, in minutes. After this length, it's abandoned due to idle.
61 const int SESSION_LIFETIME = 45;
63 public void Dispose ()
68 public void Init (HttpApplication context)
70 _sessionTable = new Hashtable();
74 //this is the code that actually do stuff.
75 public bool UpdateContext (HttpContext context)
77 SessionContainer container = null;
79 //first we try to get the cookie.
80 // if we have a cookie, we look it up in the table.
81 if (context.Request.Cookies [COOKIE_NAME] != null) {
82 container = (SessionContainer) _sessionTable [context.Request.Cookies [COOKIE_NAME].Value];
84 // if we have a session, and it is not expired, set isNew to false and return it.
85 if (container!=null && container.SessionState!=null && !container.SessionState.IsAbandoned) {
86 // Can we do this? It feels safe, but what do I know.
87 container.SessionState.IsNewSession = false;
88 // update the timestamp.
90 // Can we do this? It feels safe, but what do I know.
91 context.SetSession (container.SessionState);
92 return false; // and we're done
93 } else if(container!=null) {
94 //A empty or expired session, lets kill it.
95 _sessionTable[context.Request.Cookies[COOKIE_NAME]]=null;
99 // else we create a new session.
100 string sessionID = System.Guid.NewGuid ().ToString ();
101 container = new SessionContainer (new HttpSessionState (sessionID, // unique identifier
102 new SessionDictionary(), // dictionary
103 new HttpStaticObjectsCollection(),
104 SESSION_LIFETIME, //lifetime befor death.
106 false, // is cookieless
107 SessionStateMode.InProc,
109 // puts it in the table.
110 _sessionTable [sessionID]=container;
113 context.SetSession (container.SessionState);
114 context.Session.IsNewSession = true;
117 // sets the session cookie. We're assuming that session scope is the default mode.
118 context.Response.AppendCookie (new HttpCookie (COOKIE_NAME,sessionID));