获取MVC自定义成员资格中PersistentCookie的值

时间:2012-10-20 19:41:08

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

我使用MVC 4,我的登录操作就像这样:

    [HttpPost]
    public ActionResult LogOn(Account loginInfo, string returnUrl)
    {
        if (this.ModelState.IsValid)
        {
            if (loginInfo.Username == "Ali" && loginInfo.Password == "110")
            {
                FormsAuthentication.SetAuthCookie(loginInfo.Username, loginInfo.RememberMe);
                FormsAuthentication.RedirectFromLoginPage(loginInfo.Username, loginInfo.RememberMe);
            }
        }
        this.ModelState.AddModelError("", "The user name or password provided is incorrect.");
        ViewBag.Error = "Login faild! Make sure you have entered the right user name and password!";
        return View(loginInfo);
    }

现在我的问题是: 我怎么能随时查看用户选中的RememberMe复选框或不用,换句话说得到PersistentCookie的值?

两个解决方案

我的解决方案

        var isPersistent = false;
        var authCookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie != null)
        {
            var ticket = FormsAuthentication.Decrypt(authCookie.Value);
            isPersistent = ticket.IsPersistent;
        }

ChunHao Tang解决方案(略有改动)

var isPersistent  = ((System.Web.Security.FormsIdentity) User.Identity).Ticket.IsPersistent;

1 个答案:

答案 0 :(得分:0)

您可以使用[授权]过滤器检查

[Authorize]
public ActionResult Contact()
{
    return View();
}

或者,您可以使用Request.IsAuthenticated来检查用户选中的rememberMe复选框或不。