How to handle session end in global.asax?

You can use global.asax's session end event to remove the unexpectedly disconnected user :

void Session_End(Object sender, EventArgs E) {
    // Clean up session resources
}

but beware, session doesn't end when the user closes his browser or his connection lost. It ends when the session timeout reached.


Add a Global.asax file to your website, and in the Session_End event, you remove the user from your HashTable.

protected void Session_End(Object sender, EventArgs e)
{
    // Remove user from HashTable
}

The Session_End event doesn't fire when the browser is closed, it fires when the server hasn't gotten a request from the user in a specific time persion (by default 20 minutes). That means that if you use Session_End to remove users, they will stay in the chat for 20 minutes after they have closed the browser.

I suggest that you keep the time of the last request in the user object. That way you can determine how active the user is, and how likely it is that the user has left the chat. You can for example show any user that has not done anything for two minutes as inactive.

You can also let the chat application poll the server periodically (if you don't do that already). This would update the last request time in the object and keep the user alive as long as the chat window is open.

You can use the onunload event in the browser to send a logout request to the server when the user leaves the page. This of course only works if the user still has net connectivity. The onunload event is also triggered when you reload the page, so you would have to keep track of why the event is triggered to use it.


You can use JavaScript which always runs on the client to send a signal to the server - like "I'm here". If next signal does not come, you can call Leave();. I used AJAX to do this.