Search code examples
asp.net-mvcc#-4.0asp.net-identity-2

How to Keep Track User Last Activity Time Using Microsoft.AspNet Identity


So I've extended default User class as ;

[Serializable]
public class AUser : IdentityUser<int, AUserLogin, AUserRole, AUserClaim>, IUser , IXmlSerializable
{
    public virtual DateTime LastActivity { get; set; }
    ...
    ...
}

And I've a method to update user activity

 public async void UpdateUserActivity(string userName)
 {
     var user =  _userManager.FindByName(userName);
     user.LastActivity = DateTime.UtcNow;
     await _userManager.UpdateAsync(user);
 }

My purpose here is to keep track of last activity time of users. By last activity time i mean the last time user did any action on the application.

I was planning to call the update method after each request is executed. However, it means executing an update on the database for each request. That sounded expensive to me.

Question : where shall i call it? Is there any better way to keep track of user last activity?

Regards,


Solution

  • You could use the OnActionExecuted event inside a controller to keep track of the user activity and write the activity log for all users into an application wide object using HttpContext.Application. To keep the traffic to your database low you could implement a global background thread, that reads the local stored activity data and writes them into youir database after a fixed time (e.g. once per minute).

    You would have less database traffic, but the activity data would not be 100% up to date. Depending on your database update cycle.