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 access开发者_JAVA百科ing 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.
- Cookies are not disabled in my browser
- I know that ASP.NET has its own session handling mechanism, just playing around and stumbled upon this cookie problem
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
.
精彩评论