Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get notified of session end?

I am wondering if I can handle a session timeout event. I need to make a function call to my function right before session timeouts or user left my page, or closed browser window. The most important part here is to have access to everything stored during the session, session variables.

like image 740
Maksim Vi. Avatar asked Dec 17 '22 06:12

Maksim Vi.


2 Answers

Take a look at the Session_End() method in global.asax. The global.asax file should already be wired to call this method when the session ends. You can just put your code in there however you'd like.

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the session ends
    End Sub

Of course, you should note that the session is entirely a server-side thing. It'll only end after X minutes of inactivity (20 minutes is the default). It will not end the instant the user closes the window. ASP.NET has no knowledge of a user closing a window or leaving your page.

And in fact, it's tricky to try to perform any immediate action on the server-side when this happens. I mean, it's easy to call window.onbeforeunload in Javascript and bring up a confirm box before the user closes the window. But when you try to send a packet to the server immediately before the window actually closes, I think you'll find that it becomes a difficult task to make this all user-friendly. You could write some Javascript that sends a message to the server using AJAX which notifies the server that the user is closing their browser, and then use more Javascript to close the browser after that message has been sent. But then the user will get the annoying message (in most browsers) stating that a script is trying to close the window. This will look very amateur-ish to the user and may make them think twice about coming back.

So if you're willing to put up with a delay, I'd just avoid this whole Javascript mess entirely and rely on a pure server-side solution using Session_End(). After all, if a user closes the window or leaves, ASP.NET will eventually notice because the session will timeout.

like image 101
Steve Wortham Avatar answered Dec 22 '22 00:12

Steve Wortham


Session_end will handle the session time out issue. However, this will not fire when the user closes the browser or moves to a different URL. It waits until the session timeout expires.

In order to detect the other conditions, you'll have to use javascript on the client. However, these methods aren't always reliable depending on the browser/version, etc. Also if the user's computer shuts down, is unplugged, or they otherwise completely go away this script won't fire.

You might consider other alternatives. What exactly are you trying to accomplish with this function?

like image 41
NotMe Avatar answered Dec 21 '22 22:12

NotMe