Asp.net mvc 5 cookies not persisting to local server

Hi I am trying to set a cookie in my mvc5 app right after the user logs in and I expect the cookie to be saved after the browser is closed, but the requested cookie seems to be empty after I close the browser (it works fine when I try to get access right after login.)

This 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 have already checked similar questions and checked my browser settings, but still I get null when I requested the cookie.

+3


source to share


1 answer


Change it to

 userCookie.Expires = DateTime.Now.AddDays(1);

      



because your previous code didn't set the cookie expiration time.

+2


source







All Articles