views:

154

answers:

3

I'm using ASP.NET Session State to keep track of logged in users on my site.

However, one problem I'm running into is that by default ASP.NET session cookies are set to expire when the browser closes.

I've tried setting my own ASP.NET_SessionId cookie and modifying the cookie's expiry using something similar to the following code:

Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(1);

None of these approaches work, they all set a second cookie with the same name.

Is there a way of changing the session cookie's expiry?

+1  A: 

Just a guess: Maybe editing the session.configuration inside the web.config could change the cookie-expiration? You can take a look here?

Olaf Watteroth
+2  A: 

I would suggest you use FormsAuthentication to track logged in users. You can use a persistent FormsAuthenticationCookie to achieve what you want.

Or if you really want to use Session State, try this technique.

Joe
The FormsAuthCookie approach just allows returning users to skip the forms login if they re-connect within a specific time window. It doesn't maintain any state that they may have previously created on the server.
ChrisW
@ChrisW - "It doesn't maintain any state that they may have previously created on the server" - of course not, such state should be persisted, e.g. to a database, e.g. using Profile.
Joe
The technique you linked to works, thanks :)
Charlie Somerville
+1  A: 

I think trying to keep session alive for a long time is the wrong approach and limits your scalability. The session cookie is pointing to a specific session that's being maintained by IIS on the server. In general, you want session to close after the user closes their browser so as to not consume all of the available server resources for inactive users. You want session for a departing user to close and the resources made available to a new arriving user. That's why the session cookie expires.

If you want to maintain some user state after the user closes their browser, you can always look at something like Profile. Or, if this is for something like a shopping cart, you can persist your shopping cart in a database and then reconnect that to the user when they log on again.

ChrisW