简体   繁体   English

ASP.NET Cookies

[英]ASP.NET Cookies

Guys, I am trying to make a website that keeps a cookie active, so long as the user is active in the site. 伙计们,我正在尝试创建一个使cookie保持活动状态的网站,只要用户在该站点中处于活动状态即可。 My idea was to create a cookie on the main page of the site, like so: 我的想法是在网站主页上创建一个cookie,如下所示:

HttpCookie cookie = new HttpCookie("KeepAlive","1");
cookie.Expires = DateTime.Now.AddMinutes(20);
Request.Cookies.Add(cookie);

If I have this code in my Page_Load event on every page, this should keep refreshing the cookie. 如果我在每个页面的Page_Load事件中都包含此代码,则应继续刷新cookie。 If, after 20 minutes, the cookie expires, it will kick them back to the main screen. 如果20分钟后cookie失效,它将把它们踢回到主屏幕。 I just want to make sure I am going about this the right way. 我只是想确保我要以正确的方式进行操作。

Thanks 谢谢

I think you should look at using session for that. 我认为您应该考虑使用会话。 With Session, you can set a timeout (20 minutes by default), and the rest will occur automatically (updating the active status, etc). 使用会话,您可以设置超时(默认为20分钟),其余时间将自动发生(更新活动状态等)。

EDIT (more on Session): 编辑(有关会话的更多信息):

By using session, the site user can be identified throughout their experience. 通过使用会话,可以在整个体验中确定站点用户。 This happens automatically, without any need for the developer to code for it or to test that it works. 这是自动发生的,无需开发人员为其编写代码或测试其是否有效。

Session is stored on the server, and is therefore safer (users can modify their cookies) 会话存储在服务器上,因此更安全(用户可以修改其Cookie)

You can run code at the start, or at the end of any session (using a global.asax file) 您可以在任何会话的开始或结尾运行代码(使用global.asax文件)

Sessions can be setup as cookieless (users may have cookies disabled) 可以将会话设置为无cookie(用户可能禁用了cookie)

You can store c# objects in session variables so that they are available through the active session (stored in server memory). 您可以将c#对象存储在会话变量中,以便可以通过活动会话(存储在服务器内存中)使用它们。

I can't think of any more advantages in this case. 在这种情况下,我想不出更多优势了。 I invite others to leave comments with their thoughts. 我邀请其他人发表自己的想法。

如果您确实要为此使用cookie, 是的,您的方法正确

这将起作用,尽管您可能想研究使用会话cookie。

您需要将cookie添加到Response对象,而不是Request对象。

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

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