简体   繁体   English

ASP.Net中的Cookie

[英]Cookies in ASP.Net

I set a cookie like this in one page: 我在一个页面中设置了这样一个cookie:

Request.Cookies["lang"].Value = "en-US";
Request.Cookies["lang"].Expires = DateTime.Now.AddDays(50); 

On another page I try and read the cookie: 在另一页上,我尝试阅读cookie:

string lang = Server.HtmlEncode(Request.Cookies["lang"].Value);

The cookie is not null but the value is an empty string. cookie不为null,但值为空字符串。 What am I doing wrong? 我究竟做错了什么?

You should be using Response.Cookies to set the cookie, and Request.Cookies to read any cookies sent back from the client. 您应该使用Response.Cookies来设置cookie,并使用Request.Cookies来读取从客户端发回的任何cookie。

The code in your question is setting the cookie in the Request object, not the Response . 您问题中的代码是在Request对象中设置cookie,而不是Response

Are cookies enabled on the client? 客户端是否启用了Cookie? The fact that you set a cookie doesn't mean that the client supports them and will send them back. 您设置cookie的事实并不意味着客户端支持它们并将其发回。

Remember, you're dealing with two disconnected systems; 请记住,您正在处理两个断开连接的系统; your server doesn't keep state and you know little about the client. 你的服务器没有保持状态,你对客户端知之甚少。

If I remember correctly I think you should be using response instead of request as request is what is being sent to you. 如果我没记错的话,我认为您应该使用响应而不是请求,因为请求是发送给您的。 Response is when you want to set something back to the client browser. 响应是指您想要将某些内容设置回客户端浏览器。

EDIT: What you are doing is modifying the cookies in that particular request which would make sense why you are not seeing on subsequent pages. 编辑:您正在做的是修改该特定请求中的cookie,这有助于您在后续页面上看不到的原因。 That is not saving them back to the client. 这不是将它们保存回客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM