Reputation: 153
Hi I am trying to set a cookie in my mvc5 application right after user logged in, and I am expecting cookie to persist after browser is closed, but requested cookie seems to be null after I closed the browser (it works fine when I try to access right after the login).
Here is how I created the 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");
}
}
I already checked the similar questions and checked my browser settings, but still I am getting null when I requested the cookie.
Upvotes: 3
Views: 1394
Reputation: 15913
Change it to
userCookie.Expires = DateTime.Now.AddDays(1);
because your former code would not set the expire time of the cookie.
Upvotes: 3