0

如果用户选中记住我复选框,我有一个登录控制器,它正在设置一个 cookie,但是如果用户下次访问我的网站并且 cookie 尚未过期,我想这样做,所以我将他重定向到产品页面。

这是控制器动作

[HttpPost]
    public ActionResult Index(MyData data)
    {
        if (ModelState.IsValid)
        {
            if (data.UserName == "abc" && data.Password == "123")
            {
                if (data.RememberMe == true)
                {
                    var authTicket = new FormsAuthenticationTicket(1, data.UserName, DateTime.Now, DateTime.Now.AddMinutes(2), data.RememberMe,"");
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
                    Response.Cookies.Add(cookie);
                    return RedirectToAction("Index", "Products");
                }
                else
                {
                    return RedirectToAction("Index", "Products");
                }
            }
            else
            {
                ModelState.AddModelError("", "Invalid User Name & Password");
            }
        }
        return View();
    }

控制器的索引动作

  public ActionResult Index()
    {
        if(//logic which is i am asking about)
        {
          return RedirectToAction("Index", "Products");
        }
        return View();
    }
4

2 回答 2

0

你试过这个吗?

if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
    {
      return RedirectToAction("Index", "Products");
    }
    return View();
}
于 2012-05-15T19:44:06.893 回答
0
if (ControllerContext.HttpContext.User.Identity.IsAuthenticated) 

是你所需要的全部。解密和过期身份验证 cookie 是表单身份验证的职责。

于 2012-05-15T19:46:47.007 回答