How to work with an open session

I am implementing a session structure.

I have a server side ConcurrentDictionary holding all the <SessionId, UserSession> .

When a new connection is established, the cookie is assigned to the client browser, perm or temp, depending on the RememberMe option.

When clients call the LogOut function, it removes the session from the dictionary.

However, when the client browser is simply closed or broken, and the cookie has been lost or expired or deleted, the server-side session object in memory remains in the dictionary and becomes a ghost. Over time, these ghosts will add up.

My question is how to improve the design so that dead sessions can be cleaned after they have expired?

I was thinking of making a timer service that runs a cleaning schedule, but it's not too elegant. Is there an easier way to do this without depending on the external service?

+6
source share
3 answers

I have a similar situation in one of my projects.

instead of a dictionary, I used a cache with a short absolute expiration and a user session identifier as a cache key:

 HttpContext.Current.Cache.Insert(sessionID, userEntity, null, DateTime.Now.AddSeconds(30), TimeSpan.Zero); 

and on the client side, I make an ajax call every 15 seconds to notify the server and update the cache for this session identifier.

therefore, whenever a user closes his browser window, the server does not receive any notifications, and the user session ID has expired automatically.

+4
source

If your sessionstate is "InProc", why not just apply your code to Session_Start and Session_End?

 void Session_Start(object sender, EventArgs e) { //Add to ConcurrentDictionary } void Session_End(object sender, EventArgs e) { // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. //Remove from ConcurrentDictionary } 
+2
source

I answer my question in a few months. If I want to have such a structure, I would use Microsoft SignalR. Because it controls sessions for me in real time and does much more.

0
source

Source: https://habr.com/ru/post/954823/


All Articles