Search code examples
asp.net-coreasp.net-identityasp.net-core-mvc

How to get the list of recently logged in user in asp.net core MVC?


I want to get the list of recently logged in user , how can I get the list of recently logged in user in asp.net core MVC ?


Solution

  • You could create model class:

     public class LoginEntry
     { 
          [Key]
          public string EntryID { get; set; }
          public string UserID { get; set; }
          public ApplicationUser User { get; set; } //represents the user who was logged
    
          public DateTime? TimeOfLastLogin { get; set; } //time when the user logged last time
      }
    

    So you need some service that do entry when user was logged:

    public class LoginEntryService
    {
      public void DoEntry(ApplicationUser user)
      {
       var entry = dbcontext.LoginEntries.SingleOrDefault(e => e.UserID == userID);
       if (entry == null) //if Entry for the user does not exist then create it
           entry = new LoginEntry() {UserID = user.ID};
       entry.TimeOfLastLogin = DateTime.UtcNow; //update the last login time
    
       if (entry.ID == null)
           dbcontext.LoginEntries.Add(entry);
    
       dbcontext.SaveChanges();
      }
    }
    

    You can call DoEnty method when the user is logging from, e.g., controller or user repository instance