【问题标题】:Remember Me - Fetch UserName - MVC记住我 - 获取用户名 - MVC
【发布时间】:2016-06-14 07:04:15
【问题描述】:

我正在开发 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);

提前致谢。

【问题讨论】:

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


    【解决方案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" })
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 2017-06-04
      • 2014-01-17
      • 2014-05-16
      • 2014-06-10
      • 2014-08-12
      相关资源
      最近更新 更多