How to handle session end in global.asax?

2019-01-03 18:14发布

I'm working in chat application, I used HashTable for containing User and Operator as a Key & Object of ChatRoom Class as a value of HashTable. Main problem is that When user or Operator close browser or disconnected without logout then It is automatically logout on the end of the session.

Please help me related to that and how to use Global.asax in this matter.

4条回答
Fickle 薄情
2楼-- · 2019-01-03 18:34

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
}
查看更多
Juvenile、少年°
3楼-- · 2019-01-03 18:41

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.

查看更多
爷的心禁止访问
4楼-- · 2019-01-03 18:48

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

查看更多
疯言疯语
5楼-- · 2019-01-03 18:53

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.

查看更多
登录 后发表回答