mvc 5设置Cookie过期,但到期时间为01/01/0001

时间:2016-01-21 13:26:42

标签: asp.net-mvc cookies

我在登录成功时设置了cookie:

public JsonResult LoginWithPassword(String password)
        {

                Response.Cookies.Remove("Auth");
                string CookieName = "Auth";
                long UserId = 4;

                HttpCookie myCookie = HttpContext.Response.Cookies[CookieName] ?? new HttpCookie(CookieName);
                myCookie.Values["UserId"] = UserId.ToString();
                myCookie.Values["LastVisit"] = DateTime.Now.ToString();
                myCookie.Expires = DateTime.Now.AddDays(1);
                HttpContext.Response.Cookies.Add(myCookie);

                return Json(new { IsSuccess = true, ReturnUrl = returnUrl });
            }
            else
            {
                return Json(new { IsSuccess = false, Message = "Login fail, Wrong Password" });
            }
        }

我在下一页/行动中看到了它:

public ActionResult Index()
        {
            if (HttpContext.Request.Cookies["Auth"] == null)
                return RedirectToAction("Login", "Access");
            return View();
        }

非常奇怪的是" Auth"总是空的。当我在调试断点中检查到期日期时,我得到到期日期:01/01/0001

为什么会发生这种情况以及如何解决这个问题? 这个动作在两个不同的控制器

1 个答案:

答案 0 :(得分:1)

我试图实现你的代码来创建cookie。在firefox浏览器中,我的MVC5中的相同代码工作正常。 我使用下面的代码创建cookie -

Response.Cookies.Remove("Auth");
                string CookieName = "Auth";
                HttpCookie cookie = HttpContext.Response.Cookies[CookieName] ?? new HttpCookie(CookieName);

//HttpCookie cookie = new HttpCookie("Cookie");

cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();

cookie.Expires = DateTime.Now.AddDays(5);
            this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);

此外,在“索引”页面上检查“Auth”cookie是否成功 -

公共ActionResult索引()

    {
        if (HttpContext.Request.Cookies["Cookie"] == null)
            return RedirectToAction("Login", "Account");
        return View();
    }

或者我建议 1)在登录页面OR中创建cookie后设置Expiry 2)在到期日加上小数,例如。 1.0或5.0。见链接文章 - http://forums.asp.net/t/1982279.aspx?MVC5+Application+Cookie+expires+when+session+ends

如果这有助于您,请告诉我。