Can Session_End fire on window close? (ASP.NET)

2019-02-15 01:27发布

问题:

I am putting an "online" counter on a website, and I have run into these two contradicting sources.

This one (I am using this example code):

http://aspdotnetfaq.com/Faq/How-to-show-number-of-online-users-visitors-for-ASP-NET-website.aspx

...says that:

Also when user closes his browser or does not click on any links in our website, session expires, and our "OnlineUsers" global variable is decreased.

However, this one:

http://www.velocityreviews.com/forums/t383710-session-end-guarantee.html

...says that:

Closing the browser window, or browsing to another site will NOT cause Session_End to fire, at least, not straightaway - the server has absolutely no way of knowing what happens on the client machine until it gets another HttpRequest from it. In this instance, Session_End will fire when the session times out naturally.

I have tested and it seems that Session_End DOES NOT fire.

I basically want you guys to confirm or comment on this.

Is it possible to update the online counter on browser-close?

回答1:

The second is true

Closing the browser window, or browsing to another site will NOT cause Session_End to fire, at least, not straightaway - the server has absolutely no way of knowing what happens on the client machine until it gets another HttpRequest from it. In this instance, Session_End will fire when the session times out naturally.

Session time out is 20 minutes by default. You can confirm this by not doing any activity on your website for 20 min.



回答2:

Your two links are not contradictory. The first link is poorly worded, but it basically says what the second link says. It would be easier to understand if it were written like this:

Also when user closes his browser or does not click on any links in our website (after a period of time) the session will expire, and our "OnlineUsers" global variable is decreased.

Also note that Session_End may not always fire, especially if the session is killed or bounced (for example, if you update the web.config, the worker process recycles, or in some cases an uncaught exception occurs).



回答3:

As is pointed out later in the first link posted the Session_End event fires after the session timeout expires. If the user who is associated with a session sends no requests to the server before the session timeout value expires the session_end event will be fired and the session will be removed from memory.

MSDN for asp.net session state: http://msdn.microsoft.com/en-us/library/ms178581.aspx