您好我正在尝试在用户登录后立即在我的mvc5应用程序中设置一个cookie,并且我希望cookie在浏览器关闭后仍然存在,但是在关闭浏览器后请求的cookie似乎为null(它工作正常时)我尝试在登录后立即访问。
以下是我创建Cookie的方法:
public ActionResult Login(User u)
{
// this action is for handle post (login)
if (ModelState.IsValid) // this is check validity
{
using (RoadTexEntities rte = new RoadTexEntities())
{
var v = rte.Users.Where(a => a.UserEmail.Equals(u.UserEmail) && a.password.Equals(u.password)).FirstOrDefault();
if (v != null)
{
var checkBox = Request.Form["rememberMe"];
if (checkBox == "on")
{
string user = JsonConvert.SerializeObject(v);
HttpCookie userCookie = new HttpCookie("user");
userCookie.Values.Add("details", user);
userCookie.Expires.AddDays(1);
Response.Cookies.Add(userCookie);
}
Session["username"] = v.UserFirst;
return RedirectToAction("AfterLogin");
}
else
{
ViewBag.Message = "Invalid Login Credentials";
}
}
}
return View(u);
}
public ActionResult Index(){
HttpCookie userCookie = Request.Cookies["user"];
if (userCookie != null)
{
return RedirectToAction("AfterLogin");
}
else
{
return RedirectToAction("Login");
}
}
我已经检查了类似的问题并检查了我的浏览器设置,但是当我请求cookie时,我仍然是null。
答案 0 :(得分:2)
将其更改为
userCookie.Expires = DateTime.Now.AddDays(1);
因为您之前的代码不会设置Cookie的过期时间。