views:

88

answers:

4

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

+2  A: 

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.

Gabriel McAdams
@Gabriel, I agree session state can be a suitable solution for this problem. Do you mind to elaborate on the advantages of session state for this functionality?
Russell
Added more information on sessions
Gabriel McAdams
Sessions are actually driven by a cookie, so they are really pretty much the same mechanism as in the question, just with a lot more overhead.
RickNZ
By default, sessions are driven by a cookie (although they don't have to be) - but by no means is it the same mechanism. For starters, the posters solution does nothing to identify the user, and would not differentiate multiple sessions by the same user.
Gabriel McAdams
A: 

If you really want to use cookies for this, Yes, You are going the right way.

this. __curious_geek
A: 

This would work, although you might want to look into using a session cookie instead.

KramerC
A: 

You need to add the cookie to the Response object, not the Request object.

RickNZ