User's last login with Forms Authentication
I need to record the last login info of a user into the database. So I'm thinking to put something like the code below in all of my controllers' action methods.
if (User.Identity.IsAuthenticated == true)
{
// sav开发者_运维百科e DateTime.Now for this user
}
However, I have a moderately huge number of controller actions. And this approach will also be difficult to manage in the long run. Is there a simpler and best way to do this?
Thanks.
[edit] With Forms Authentication, when the logon form's "remember me" is checked, the next time the user comes back they don't go to the login page anymore. That's the reason I came up with the idea above. But I really don't like it and I will appreciate your suggestions.
The built-in MembershipUser
type (which you are likely using) has a LastLoginDate
and a LastActivityDate
property. You should use those if possible.
If not, you can handle both "last login" and "last access" with an 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
}
}
If you're using MVC you could create a custom action filter and apply it to your controllers.
精彩评论