我需要将用户的最后登录信息记录到数据库中。所以我想在我的所有控制器的动作方法中加入类似下面的代码。
if (User.Identity.IsAuthenticated == true)
{
// save DateTime.Now for this user
}
但是,我有大量的控制器操作。从长远来看,这种方法也难以管理。有更简单,最好的方法吗?
感谢。
[编辑] 使用表单身份验证,当检查登录表单的“记住我”时,下次用户返回时,他们不再进入登录页面。这就是我提出上述想法的原因。但我真的不喜欢它,我会很感激你的建议。
答案 0 :(得分:1)
内置MembershipUser
类型(您可能正在使用)具有 LastLoginDate
和LastActivityDate
属性。如果可能的话,你应该使用它们。
如果没有,您可以使用HttpModule
处理“上次登录”和“上次访问”:
public class LastTimeModule : IHttpModule
{
public void Init(HttpApplication context)
{
// This event is raised prior to *any* handler request ("last access")
context.PreRequestHandlerExecute += new EventHandler(OnPreRequest);
// This event is raised when a user is authenticated ("last login")
context.PostAuthenticateRequest += new EventHandler(OnPostAuthenticateRequest);
}
void OnPostAuthenticateRequest(object sender, EventArgs e)
{
// Log time here
}
public void OnPreRequest(Object source, EventArgs e)
{
// Log time here
}
}
答案 1 :(得分:0)
如果您正在使用MVC,则可以创建自定义操作过滤器并将其应用于您的控制器。