Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get numbers of online users using .NET Identity 2.0 in MVC 5

Do guys know that how to get numbers of online users using .NET identity 2.0 membership providers in MVC 5 ?

I have scan the methods in UserManager that Identity sample gives but no helping.

like image 221
Randolph Avatar asked Apr 16 '14 23:04

Randolph


1 Answers

This should be somewhat accurate at displaying the user count. It uses a cache to store the user's IP address and returns a count of individual IPs. If two people are behind the same proxy it will count it as one person.

using System.Runtime.Caching;

public int UsersOnlineCount
{
    get
    {
        return MemoryCache.Default.Where(kv => kv.Value.ToString() == "User").Count();
    }
}

The best way of making sure everyone gets added to the cache is to define some BaseController with this in the constructor...

public BaseController() : base() 
{
    CacheItemPolicy policy = new CacheItemPolicy();
    policy.AbsoluteExpiration = DateTime.UtcNow.AddMinutes(20);

    MemoryCache.Default.Add(System.Web.HttpContext.Current.Request.UserHostAddress, "User", policy);
}
like image 160
James Sampica Avatar answered Sep 28 '22 23:09

James Sampica