如何获得会话结束的通知? [英] How to get notified of session end?

查看:25
本文介绍了如何获得会话结束的通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以处理会话超时事件.我需要在会话超时或用户离开我的页面或关闭浏览器窗口之前对我的函数进行函数调用.这里最重要的部分是访问会话期间存储的所有内容,会话变量.

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.

推荐答案

查看 global.asax 中的 Session_End() 方法.global.asax 文件应该已经连接到会话结束时调用此方法.您可以随心所欲地将代码放在那里.

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

当然,您应该注意会话完全是服务器端的事情.它只会在 X 分钟不活动后结束(默认为 20 分钟).它不会在用户关闭窗口的瞬间结束.ASP.NET 不知道用户关闭窗口或离开您的页面.

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.

事实上,当这种情况发生时,尝试在服务器端立即执行任何操作是很棘手的.我的意思是,在 Javascript 中调用 window.onbeforeunload 并在用户关闭窗口之前打开一个确认框很容易.但是,当您尝试在窗口实际关闭之前立即将数据包发送到服务器时,我认为您会发现让这一切变得对用户友好是一项艰巨的任务.您可以编写一些 Javascript,使用 AJAX 向服务器发送消息,通知服务器用户正在关闭他们的浏览器,然后在发送该消息后使用更多的 Javascript 关闭浏览器.但是随后用户会收到烦人的消息(在大多数浏览器中),指出脚本正在尝试关闭窗口.这对用户来说看起来非常业余,可能会让他们三思而后行.

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.

因此,如果您愿意忍受延迟,我将完全避免整个 Javascript 混乱,并依靠使用 Session_End() 的纯服务器端解决方案.毕竟,如果用户关闭窗口或离开,ASP.NET 最终会注意到,因为会话将超时.

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.

这篇关于如何获得会话结束的通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆