Download Free Source Code Sample :List_Active_Sessions_In_ASP_NET_Web_Form_MVC.zip


Introduction

In this article we are going to see how can we can we track active users in ASP.NET (Web Form & MVC) web application, and to answer questions like How to get online users count? Track/get active user information? etc.

We are going to do it in four steps:

  1. Creating Session Repository

  2. Setting web.config Configuration

  3. Storing Session Data

  4. Removing Session Data

  5. Show Online User (Active Sessions) Count

Background

Please download sample code so that you can follow code along with documentation. Sample code is created using ASP.NET (MVC) framework using Visual studio 2013.

UsingMultipleModules_ASP_NET_MVC_1

Creating Session Repository In ASP.NET (Web Form and MVC)

Add class file ‘ActiveSessions.cs’ and add code listed below.


public static class ActiveSessions
 {
 private static List<string> _sessionInfo;
 private static readonly object padlock = new object();

 public static List<string> Sessions
 {
 get
 {
 lock (padlock)
 {
  if (_sessionInfo == null)
  {
  _sessionInfo = new List<string>();
  }
  return _sessionInfo;
 }
 }
 }

 public static int Count
 {
 get
 {
 lock (padlock)
 {
  if (_sessionInfo == null)
  {
  _sessionInfo = new List<string>();
  }
  return _sessionInfo.Count;
 }
 }
 }
 }

Setting web.config Configuration In ASP.NET (Web Form and MVC)

Set session state as “InProc’


<system.web> 
	<sessionState mode="InProc" />
</system.web>

Storing Session Data In ASP.NET (Web Form and MVC)

In Session_Start method in global.asax.cs will be adding session value to repository (ActiveSessions).


protected void Session_Start(object sender, EventArgs e)
 {
 ActiveSessions.Sessions.Add(Session.SessionID);
 }

Removing Session Data In ASP.NET (Web Form and MVC)

When users are out of website following code will be removing its entry from repository (ActiveSessions)


protected void Session_End(object sender, EventArgs e)
 {
 ActiveSessions.Sessions.Remove(Session.SessionID);
 }

Closing the browser window, or browsing to another site will NOT cause Session_End to fire, at least, not straightaway - the server has absolutely no way of knowing what happens on the client machine until it gets another HttpRequest from it. In this instance, Session_End will fire when the session times out naturally. Default Session time out is 20 minutes.

Show Online Users (Active Sessions) Count In ASP.NET (Web Form and MVC)

Now that we have session information stored in ActiveSessions object, we can show online users count as follows-

Code For MVC 4


<%=NamespaceOfActiveSessionClassFile.ActiveSessions.Count %>

Code For MVC 5


@NamespaceOfActiveSessionClassFile.ActiveSessions.Count

Please like this article on social site if this worked for you… Coding is fun !!! Isn't it...