I am playing around again with ASP.NET, and tried to set a cookie in one action which will be read in another action.
The strange thing is: the cookie gets set, but looses 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 is like this: first I access /Home/DoLogin
, then I get redirected to /Home/About
which should actually output the value of the sid
cookie. But the cookie does not have any value.
Thanks for any hints!
In your About
action, use Request.Cookies
instead.
As a short explanation: When you set something in Response.Cookies
, that cookie is sent to the client which stores it. On each subsequent Request to the same namespace, until the expiry date is reached, the client sends that cookie to the server, which stores it in Request.Cookies
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With