浏览器关闭时调用页面方法
您好,我正在尝试在 bodyunload 方法上调用 [webmethod]。
但它仅在页面加载本身时被触发。 我该如何预防?
这是我正在使用的代码:
[WebMethod]
public static void AbandonSession()
{
HttpContext.Current.Session.Abandon();
}
<script language="javascript" type="text/javascript">
//<![CDATA[
function HandleClose() {
PageMethods.AbandonSession();
}
//]]>
</script>
<body onunload="HandleClose()">
....
....
....
</body>
谢谢, 纳古
Hi here I'm trying to call a [webmethod] on bodyunload method.
But it is getting fired on page load itself only. How do i prevent it?
Here's the code I am using:
[WebMethod]
public static void AbandonSession()
{
HttpContext.Current.Session.Abandon();
}
<script language="javascript" type="text/javascript">
//<![CDATA[
function HandleClose() {
PageMethods.AbandonSession();
}
//]]>
</script>
<body onunload="HandleClose()">
....
....
....
</body>
Thank you,
Nagu
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我已经用下面的代码进行了测试,它工作正常。
在 Aspx 页面中
在代码隐藏中
您可以在 AbandonSession 方法处放置断点,以验证它在卸载时是否受到命中。
I have tested with below code and it is working fine.
In Aspx page
In Codebehind
You can put breakpoint at AbandonSession method to verify that it is getting hit at unload.
你试图做的事情是一个坏主意。 考虑在会话中放入较少的数据,或降低超时。
也许您没有意识到 onunload 在用户刷新或离开页面时触发。 因此,假设您的代码确实有效,如果您用户刷新了他们的页面,那么他们的会话将被终止。 如果他们访问网站上的任何其他页面,他们的会话也将被终止!
可能不是您所希望的功能!
What you are attempting to do is a bad idea. Consider putting less data in the session, or lowering the timeout.
Perhaps you don't realise that onunload fires when the user refreshes or navigates away from the page. So assuming your code actually worked, if you user refreshed their page then their session would be terminated. If they visited any other page on the site their session would also be terminated!
Probably not the functionality you were hoping for!
没有办法一致地处理此类事件。 导致会话“结束”的原因太多。 其中最简单的就是连接丢失或关闭。 在这种情况下,任何触发的 JavaScript 将永远不会到达服务器。
即使你可以按照你想要的方式让它工作,它也只能在部分时间起作用。 如果您不能依赖它,您可能会花费时间并寻求不同的解决方案。
There is no way to consistently handle this type of event. There are too many causes for a session to "end". The very simplest of these would be a lost or closed connection. In this case any JavaScript fired off would never reach the server.
Even if you can get this working the way you want it is only going to work part of the time. If you can't rely on it your time may be spent and a different solution.
已经好几年了,但我不知道WebMethod可以是静态的。
It's been a few years, but I didnt know WebMethod can be static.