简单会员:用户的上次登录日期

时间:2013-01-14 15:45:31

标签: asp.net-mvc-4

我在asp.net MVC 4应用程序中使用简单成员资格。我如何获得用户的上次登录日期。我没有看到在默认的网页架构表中创建日期?我是否需要在简单会员资格中为LastLogin日期创建字段? 感谢

1 个答案:

答案 0 :(得分:10)

我已经解决了这个问题:

  1. 我在UsersContext中向UserProfile模型添加了一个LastLogin字段:

    [Table("UserProfile")]
    public class UserProfile 
    {    
        [Key]    
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        public virtual string UserName { get; set; }
        public virtual DateTime? LastLogin { get; set; }
    }
    
  2. 我修改了AccountController中的登录方法:

    public ActionResult Login(LoginModel model, string returnUrl)
    {            
        if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))     
        {
            using (UsersContext db=new UsersContext())                
            {
                UserProfile  userProfile = db.UserProfiles.SingleOrDefault(u=>u.UserName==model.UserName);
                userProfile.LastLogin = DateTime.Now;
                db.Entry(userProfile).State=EntityState.Modified;
                db.SaveChanges();
            }
    
            return RedirectToLocal(returnUrl);
        }
    
        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    } 
    
  3. 然后我像下面的方式一样获取UserProfiles:

    public ActionResult Index()
    {
        return View("Index",_db.UserProfiles);
    }
    
  4. 最后,我在Index.cshtml中显示了LastLogin DateTime:

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.UserName)
            </td>  
            <td>
                @Html.DisplayFor(modelItem => item.LastLogin)
            </td>
        </tr>
    }