如何从加密cookie中读取值?

时间:2012-05-15 19:32:49

标签: asp.net-mvc asp.net-mvc-3

如果用户选中“记住我”复选框,我有一个设置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();
    }

2 个答案:

答案 0 :(得分:0)

你试过这个吗?

if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
    {
      return RedirectToAction("Index", "Products");
    }
    return View();
}

答案 1 :(得分:0)

if (ControllerContext.HttpContext.User.Identity.IsAuthenticated) 

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