Why is my cookie not set?

I play again with ASP.NET and try to set a cookie in one action, which will be read in another action.

The strange thing is: a cookie receives a set, but loses its value when accessing another page. Here is my simple controller code:

public class HomeController : Controller { public ActionResult About() { var cookie = Response.Cookies.Get("sid"); ViewData["debug"] = "Id: " + cookie.Value; return View(); } public ActionResult DoLogin() { var cookie = new HttpCookie("sid", Guid.NewGuid().ToString()); cookie.HttpOnly = true; Response.Cookies.Add(cookie); return RedirectToAction("About"); } } 

The flow looks like this: first I go to /Home/DoLogin , then it redirects to /Home/About , which should actually output a cookie sid . But a cookie has no value.

  • Cookies in my browser are not disabled.
  • I know that ASP.NET has its own session processing mechanism, just playing around and stumbled upon this cookie problem.

Thanks for any tips!

+6
c # cookies asp.net-mvc
source share
1 answer

In your About action, use Request.Cookies .

As a brief explanation: when you set something in Response.Cookies , this cookie is sent to the client that stores it. In each subsequent request for the same namespace, before the expiration date is reached, the client sends this cookie to the server, which stores it in Request.Cookies .

+9
source share

All Articles