Or do this :
First of all you need to add these lines to your global.asax file:
(if you do not have it, open your site in Visual Studio and create it by right-clicking on website in solution explorer, selecting Add New Item > Global Application Class option)
void Application_Start(object sender, EventArgs e)
{
Application["OnlineUsers"] = 0;
}
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
Application.UnLock();
}
In this way, when a web visitor opens your website in his browser, a new session is created for him and our "OnlineUsers" variable is increased. Moreover when user session expires (user closes his browser or he does not navigate on website), our "OnlineUsers" global variable is decreased.
Now we need to edit our web.config file, enable sessionstate and configure it:
<system.web>
<sessionState mode="InProc" cookieless="false" timeout="15" />
</system.web>
Timeout value configures how many minutes our sessions are kept 'alive', then in this case if a user will be inactive for 15 minutes, he will be considered Offline.
Now you can show the number of online visitors/users and the the list of logged users (if you use asp.net membership on your website).
Add to your aspx page:
<h2> Online Users </h2>
- TotalUsers: <asp:Literal ID="TotalUsers" runat="server"></asp:Literal><br /><br />
Registered users now online: <asp:Label ID="OnlineNow" runat="server"></asp:Label>
and in codebehind:
protected void Page_Load(object sender, EventArgs e)
{
string totalUsers = Application["OnlineUsers"].ToString();
TotalUsers.Text = totalUsers;
var onlineUsers = (from a in Membership.GetAllUsers().Cast<MembershipUser>().ToList()
where a.IsOnline
select a.UserName).ToList();
string users = "no one";
for (int i = 0; i < onlineUsers.Count; i++)
users = users + " - " + onlineUsers[i];
OnlineNow.Text = users;
}