How to Save and Recover All Sessions of a User

Asked

Viewed 1,301 times

1

I am developing a system in which I need to recover all users logged in or with active session on the server.

Context: When the user logs into the system, in addition to creating the Session, save in the database your information with date of logon and session time.

Session["exemplo"] = exemplo;

When the user does logoff I drop the Session and change the information in the database. By following this structure I can have "in hand" all logged in users. The problem that occurs to me is when the user gets idle time and the session automatically drops or when the user closes the browser. That way I can no longer change the status of the same in the database.

I wonder if there is a way to recover all active Session on a server, ie, recover all users who are still logged in to the system and that their Sessions have not expired yet?

Has anyone ever done anything like this?

2 answers

5

You can store the list of sessions enabled as an Application item. So:

public void Session_OnStart()
{
    if (Application["SessionList"] == null)
        Application["SessionList"] = new List<HttpSessionState>();

    var sl = (List<HttpSessionState>) Application["SessionList"];

    sl.Add(Session);

    Application["SessionList"] = sl;
}

Do the same, but remove the session when the event Session_OnEnd occur.

  • The List data type does not accept the Session type!

  • You are correct, @Marcusurbano - I used the wrong mention. Request.Session is Httpsessionstate type. I changed the example code.

  • I ran some tests and I can still only see my user on the list. When I ask someone to log into the system, the same thing is done for them, only the list of Session that I see is not added. I need to see when a person logs into the system.

0

Following @Onosendai’s line, you could use code like this in your Global.asax:

public void Application_OnStart()
{
  Application["UsersOnline"] = 0;
}

public void Session_OnStart()
{
  Application.Lock();
  Application["UsersOnline"] = (int)Application["UsersOnline"] + 1;
  Application.UnLock();
}

public void Session_OnEnd()
{
  Application.Lock();
  Application["UsersOnline"] = (int)Application["UsersOnline"] - 1;
  Application.UnLock();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.