ASP.Net MVC Cookies Not Saved

Essentially, I'm trying to set a cookie after a user logs in to save my username the next time I log in. Here is my code for setting cookies. When I look at the site’s cookies in Firefox, as soon as a cookie is set, it displays a sessionID cookie, but not the one I just set. When I check the headers in Fiddler, I don’t see it setting a cookie, only my cookie sessionID.

HttpCookie hc = new HttpCookie("username", model.UserName); hc.Expires = DateTime.Now.AddYears(1); System.Web.HttpContext.Current.Request.Cookies.Add(hc); 

This is where I check if a cookie exists.

 if (System.Web.HttpContext.Current.Request.Cookies["username"] != null) 

Here is the full context of the methods in question.

 public ActionResult LogOn() { if (System.Web.HttpContext.Current.Request.Cookies["username"] != null) return View(new LogOnModel { UserName = System.Web.HttpContext.Current.Request.Cookies["username"].Value }); else return View(); } [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (MembershipService.ValidateUser(model.UserName, model.Password)) { HttpCookie hc = new HttpCookie("username", model.UserName); hc.Expires = DateTime.Now.AddYears(1); System.Web.HttpContext.Current.Request.Cookies.Add(hc); FormsService.SignIn(model.UserName, model.RememberMe); if (!String.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } return View(model); } 
+6
source share
1 answer

Add to response.cookies not request.cookies

+9
source

Source: https://habr.com/ru/post/887243/


All Articles