简体   繁体   中英

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. My idea was to create a cookie on the main page of the site, like so:

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. If, after 20 minutes, the cookie expires, it will kick them back to the main screen. 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).

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)

You can run code at the start, or at the end of any session (using a global.asax file)

Sessions can be setup as cookieless (users may have cookies disabled)

You can store c# objects in session variables so that they are available through the active session (stored in server memory).

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对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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