views:

7793

answers:

6

I have an ASP.net page. When I am closing the webpage I need to clear the session variables.

How to to handle this I need to maintain the timeout to 20 minutes. If he closes and login for any number of times in the 20 minutes timed out time

Is there any possiblity for clearing the ASP.net session id

+2  A: 

[EDIT] As others have suggested, your session should time out eventually, but if you want to close the session before the timeout (for example to clean up large session objects) AND have javascript available to you...

You can do this with an window.onbeforeunload handler that posts back to a sign out page.

function CloseSession( )
{
    location.href = 'SignOut.aspx'; 
}
window.onbeforeunload = CloseSession;

You could also do it via AJAX. The SignOut.aspx page (or whatever platform you are using) should abandon the user's session.

tvanfosson
Just be prepared that in the event of the browser crashing this will not get called.
Martin Brown
Please be aware of XSS (http://www.codinghorror.com/blog/archives/001171.html)
GvS
+3  A: 

I think the only good way to do this is by setting a timeout on the session variables on the server. A web server has no way to know for sure whether a user has closed his browser or not.

Javascript is not a good option, since you can disable it client-side.

dub
Not only that, but the browser may crash, the network connection may drop etc etc...
Martin Brown
+1  A: 

What if the browser process ends?

Here is a trick

You should not have so many session variables that they require cleanup. See this post for other options.

StingyJack
+2  A: 

You cannot do that.

  1. You cannot rely on a event happening on the browser
  2. There is no way the server can contact the browser to see if it is alive

You do not control the browser of the end-user. The user might close the browser, crash, disconnect from the Internet, have javascript disabled or crashed, etc, etc. Or the user might just enter another url (and after that the user might return to your page by using the back button, and expect to continue his/her session with your site).

The window.onbeforeunload is triggered with every unload of the page. Even if the user browses to another page on your site, so they might need your session again.

GvS
A: 

I don't know specifically how ASP.Net implements its sessions, but part of the Cookie RFC is that session cookies (ones without a specific 'expires' date) are purged whenever the browser is closed.

Surely there's a way to get ASP.Net using proper session cookies rather than ones with a fixed timeout?

Gareth
+1  A: 

Sorry, but I think you might be trying to solve the wrong problem here.

Why do you need to clear session state immediately?

Kramii