让用户最后访问的时间



我正在为我的ASP.NET Core API使用IdentityServer 4(带有SQL存储(。我想在数据库中某个地方的某个地方添加一个"最后访问"字段,该字段可用于在用户搜索端点中订购我的一种用户类型。理想情况下,这将显示他们上次在系统中执行动作。

如果我在登录方法中执行此操作,则不会准确,因为它只有在最初生成一个令牌时才会更新。我可以在用户访问的每个端点上添加一种方法,但这并不是正确的解决方案,因为它会重复自己。

维护用户上次访问系统时记录数据库字段的正确位置和方法是什么?

用于录制用户活动时间,您可以尝试使用每个请求的中间件。
这是步骤。
1. ADD字段到Applicationuser,该字段是存储最后访问的时间

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

2.run命令添加移民lastaccessed update-database
3. ADD中间件基于用户名

更新最后访问的时间
        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();
                }
            }
        });

我为我在identity server项目中使用集中解决方案(使用IEventSink(中的集中解决方案添加了一个答案。我们有30多个API,我发现最好仅在一个地方进行解决方案,而不是在每个API中进行解决方案。因此,我在此处添加了这个答案,以防万一任何人遇到并且有与我的要求相同的要求。这是我的答案

最新更新