获取用户上次访问时间 [英] Get users last accessed time

查看:124
本文介绍了获取用户上次访问时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的asp.net核心API使用IdentityServer 4(带有sql存储).我想在数据库中的某处添加一个最近访问"字段,该字段可用于在用户搜索端点中对我的一种用户类型进行排序.理想情况下,这将显示他们上一次在系统中执行操作的时间.

I am using IdentityServer 4 (with sql storage) for my asp.net core API. I would like to add a "Last Accessed" field somewhere in the database that can be used to order one of my user types in a user search endpoint. Ideally this would show the last time they performed an action in the system.

如果我在登录方法中这样做,将是不准确的,因为它只会在最初生成令牌时更新.我可以向用户访问的每个端点添加一个方法,但这并不像是正确的解决方案,因为它会重复我自己.

If I do this in the login method it won't be accurate as it will only update when a token is initially generated. I could add a method to every endpoint that the user accessed but this doesn't feel like the right solution as it would be repeating myself.

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

What is the correct place and method for maintaining a database field that records the last time a user accessed the system?

推荐答案

要记录用户的活动时间,可以尝试使用将针对每个请求调用的中间件.
这是步骤.
1.将字段添加到ApplicationUser中,以存储上次访问时间

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命令添加迁移LastAccessed 更新数据库
3.添加中间件以根据用户名更新上次访问时间

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();
                }
            }
        });

这篇关于获取用户上次访问时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆