ASP.Net MVC - Cookie记住我

时间:2017-01-19 16:18:29

标签: asp.net-mvc

您好试着创建一个简单的用户名cookie。 似乎添加,但当我刷新页面时,cookie已经消失,任何想法?

 [HttpGet]
            public ActionResult Login()
            {
                var model = new ViewModels.UserCredentials();
                ViewBag.Title = "Login";
                model.UserName = CheckLoginCookie();
                model.RememberMe = !string.IsNullOrEmpty(model.UserName);
                return View("Login",model);
            }
     private string CheckLoginCookie()
            {
                    if (Response.Cookies.Get("username") != null)
                    {
                        return Response.Cookies["username"].Value;
                    }

                return string.Empty;
            }

     [HttpPost]
    public ActionResult Login(ViewModels.UserCredentials credentials)
    {
    //do lots of stuff
    //Create username remember cookie
                if (credentials.RememberMe)
                {
                    HttpCookie ckUserName = new HttpCookie("username");
                    ckUserName.Expires = DateTime.Now.AddSeconds(500)
//yeap i know its only 500;
                    ckUserName.Value = credentials.UserName;
                    Response.Cookies.Add(ckUserName);
                }

    }

1 个答案:

答案 0 :(得分:3)

要检查来自客户端的cookie,您需要查看Request not the Response。

private string CheckLoginCookie()
{
    if (Request.Cookies.Get("username") != null)
    {
        return Request.Cookies["username"].Value;
    }
    return string.Empty;
}