Get last login of the user

Asked

Viewed 269 times

1

In my project I came up with this business rule.

I need to pick up the last time the user logged in to the system. So it would be something so that I could catch the day and time of the last login.

I already have the column created in the database called UltimoLogin which is a DateTime.

Can someone help me?

Code of Controller

Autenticacaocontroller

 [HttpPost]
    public ActionResult Index(String Login, String Senha)
    {
        //verificando login pelo usuario do banco de dados ...
        Usuario login = db.Usuarios.Where(x => x.Login == Login && x.Senha == Senha).FirstOrDefault();

        if (login != null)
        {
            FormsAuthentication.SetAuthCookie(login.Nome.ToString(), false);
            Session.Add(".PermissionCookie", login.Perfil);
            Session.Add("UsuarioID", login.UsuarioID);
            return RedirectToAction("Index", "Home"); // página padrão para todos os usuários
        }

        return RedirectToAction("Index");           
    }

1 answer

2


You can do so, when you are logging in seven user property UltimoLogin for DateTime.Now and save the modifications. If this db is an instance of a DbContext Entity Framework would look like this

[HttpPost]
public ActionResult Index(String Login, String Senha)
{
    //verificando login pelo usuario do banco de dados ...
    Usuario login = db.Usuarios.Where(x => x.Login == Login && x.Senha == Senha).FirstOrDefault();
    if (login != null)
    {
        FormsAuthentication.SetAuthCookie(login.Nome.ToString(), false);
        Session.Add(".PermissionCookie", login.Perfil);
        Session.Add("UsuarioID", login.UsuarioID);
        login.UltimoLogin = DateTime.Now;
        db.Entry<Usuario>(login).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index", "Home"); //pagina padrao para todos os usuarios...
    }
    return RedirectToAction("Index");

}

And basically when you need this data is just you take the value of that column. If, as I imagined, you are using the Entity Framework, it will already put the value for you in the property UltimoLogin of the object Usuario. The enumeration EntityState is in the namespace System.Data.Entity

Browser other questions tagged

You are not signed in. Login or sign up in order to post.