I am playing around again with ASP.NET, and tried to set a cookie in one action which will be read in another action.
我正在玩ASP.NET,并尝试在一个动作中设置一个cookie,这个动作将在另一个动作中读取。
The strange thing is: the cookie gets set, but looses its value when accessing another page. Here is my simple controller code:
奇怪的是:cookie被设置,但在访问另一个页面时失去了它的价值。这是我简单的控制器代码:
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.
流程是这样的:首先我访问/ Home / DoLogin,然后我被重定向到/ Home / About哪个应该实际输出sid cookie的值。但是cookie没有任何价值。
- 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
我的浏览器未禁用Cookie
我知道ASP.NET有自己的会话处理机制,只是玩弄并偶然发现这个cookie问题
Thanks for any hints!
谢谢你的任何提示!
1 个解决方案
#1
9
In your About
action, use Request.Cookies
instead.
在“关于”操作中,请改用Request.Cookies。
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
.
作为一个简短的解释:当您在Response.Cookies中设置某些内容时,该cookie将被发送到存储它的客户端。在到达相同名称空间的每个后续请求中,在到达到期日期之前,客户端将该cookie发送到服务器,服务器将其存储在Request.Cookies中。
#1
9
In your About
action, use Request.Cookies
instead.
在“关于”操作中,请改用Request.Cookies。
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
.
作为一个简短的解释:当您在Response.Cookies中设置某些内容时,该cookie将被发送到存储它的客户端。在到达相同名称空间的每个后续请求中,在到达到期日期之前,客户端将该cookie发送到服务器,服务器将其存储在Request.Cookies中。