5

I need to count number of sessions but it dose not work when I say if numbers of sessions are 2 then do something. The example below is my code:

  // count curent session in order to keep two player
  if (HttpContext.Current.Session.Count == 2)
  {
     Response.Redirect("update.aspx");
  }

I place the above code in code behind. is there any other way that I can say: if number of sessions are 2 else do something...

leppie
  • 115,091
  • 17
  • 196
  • 297
Sam Jelveh
  • 237
  • 1
  • 3
  • 17
  • 1
    The Count property is used for getting the number of items in the session-state collection. – CD.. Jul 07 '11 at 10:15
  • the session object contains some asp.net sessions too, not just the ones you have placed. why don't you put a line break (shortcut key: F9) and see the count? – iamserious Jul 07 '11 at 10:16
  • Sometimes opening in 2 windows in same browser (will not count as two sessions.Sometimes even from different browser same problem might occur. Please open the webpage from two systems (I am not sure; sorry) – Ganesh Jul 07 '11 at 10:17

3 Answers3

3

This is the count of session variables stored in the session for that user (msdn reference)...not the number of user sessions that exist currently.

You will need to store the session count outside of the session itself...perhaps in the Cache or Application cache.

Here are some SO questions to help implement this:

Community
  • 1
  • 1
davidsleeps
  • 9,393
  • 11
  • 59
  • 73
0

NOTE: this example is just for a novice programmer (NOT for ASP expert programers)

1) Go to Global.asax.cs file and identify the application startup function and then add a Session counter variable. Like this...

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup                                       
        Application.Add("NOF_USER_SESSION", 0);

2) Then in the same GLobal.asax.cs file keep adding/reducing the user counts in Session-Startup and Session-Endup function respectively... like this...

     void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started
            Application["NOF_USER_SESSION"] =          (int)Application["NOF_USER_SESSION"] + 1;
..
..
        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // 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.
            Application["NOF_USER_SESSION"] = (int)Application["NOF_USER_SESSION"] - 1;
..
..

3) Then use this Application level variable (int)Application["NOF_USER_SESSION"] wherever you can inside your program.

Kiquenet
  • 14,494
  • 35
  • 148
  • 243
  • need to use Application.Lock/UnLock, as in https://stackoverflow.com/a/41192294/903783 to avoid race condition (since sessions may be created/terminated in parallel while you read and try to increment/decrement and set a value in that dictionary) – George Birbilis Jan 07 '19 at 09:53
0

I've found the Session_Start Session_End somewhat unreliable, Session_End sometimes does not seem to be called. This is what I use, it maintains a dictionary of client IP address and last access date, timing out "sessions" after 20 minutes. Here I store the count in a static property called NumberOfSessions in a custom base class derived from Controller.

    public void Application_BeginRequest()
    {
        Application.Lock();
        string addr = Request.UserHostAddress;
        Dictionary<string, DateTime> sessions = Application["Sessions"] as Dictionary<string, DateTime>;
        sessions[addr] = DateTime.Now;
        List<string> remove = new List<string>();
        foreach(KeyValuePair<string, DateTime> kvp in sessions)
        {
            TimeSpan span = DateTime.Now - kvp.Value;
            if (span.TotalMinutes > 20)
                remove.Add(kvp.Key);
        }
        foreach (string removeKey in remove)
            sessions.Remove(removeKey);
        BaseController.NumberOfUsers = sessions.Count;
        Application.UnLock();
    }