Get users last accessed time

孤街醉人 提交于 2019-12-06 14:06:28

For recording the user active time, you could try Middleware which will be called for every request.
Here are steps.
1.Add field to ApplicationUser which is store the last accessed time

public class ApplicationUser : IdentityUser
{       
    public DateTime LastAccessed { get; set; }
}

2.run command add-migration LastAccessed and update-database
3.Add middleware to update the last accessed time based on the user name

        app.UseAuthentication();
        app.Use(async (context, next) => {
            await next.Invoke();
            //handle response
            //you may also need to check the request path to check whether it requests image
            if (context.User.Identity.IsAuthenticated)
            {
                var userName = context.User.Identity.Name;
                //retrieve uer by userName
                using (var dbContext = context.RequestServices.GetRequiredService<ApplicationDbContext>())
                {
                    var user = dbContext.ApplicationUser.Where(u => u.UserName == userName).FirstOrDefault();
                    user.LastAccessed = DateTime.Now;
                    dbContext.Update(user);
                    dbContext.SaveChanges();
                }
            }
        });

I added an answer for a similar question which I did with a centralized solution in the identity server project (using IEventSink). We have 30+ apis and I found it better to do the solution in only one place instead of doing it in each and every api. So i added this answer here just in case anybody came across and have the same requirements as mine. This is my answer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!