记住我 - 获取用户名 - MVC

时间:2016-06-14 07:04:16

标签: asp.net asp.net-mvc authentication remember-me

我正在研究ASP.NET MVC5应用程序,我想实现RememberMe功能。在这里,当用户检查RememberMe时,只要用户再次访问该网站,就应该自动将用户名提取到用户名字段。我试过以下方法。但它有问题,我无法做到这一点。任何人都可以帮我这样做吗?

var authTicket = new FormsAuthenticationTicket(
                                           1,
                                           userId,  //user id
                                           DateTime.Now,
                                           DateTime.Now.AddMinutes(50),  // expiry
                                           model.RememberMe,  //true to remember
                                           string.Empty
                                         );

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
if (authTicket.IsPersistent)
{
    cookie.Expires = authTicket.Expiration;
}
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);

提前致谢。

1 个答案:

答案 0 :(得分:1)

我通过使用以下代码完成了此操作。 在控制器中: 在登录POST操作中:

if(model.RememberMe == true)
                    {
                        Response.Cookies["email"].Value = model.Email;
                        Response.Cookies["email"].Expires = DateTime.Now.AddDays(365);
                    }

登录初始行动:

if (Request.Cookies["email"] != null)
                ViewBag.email = Request.Cookies["email"].Value;

在视图中:

@if (ViewBag.email != null)
    {
    @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @Value = ViewBag.email })
    }
    else
    {
     @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
    }
相关问题