2009-07-07 64 views
0

嗨,这里我试图调用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> 

谢谢 纳古

+0

请显示代码。 – 2009-07-07 10:47:26

+0

你可以发布一些代码来说明发生了什么? – 2009-07-07 10:47:33

回答

3

我测试过下面的代码,它工作正常。

在ASPX页面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 

    <script type="text/javascript"> 
     //<![CDATA[ 

     function HandleClose() 
     { 


      PageMethods.AbandonSession(); 
     } 

     //]]>  
    </script> 

</head> 
<body onunload="HandleClose()"> 
    <form id="form1" runat="server"> 
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> 
    </asp:ScriptManager> 
    </form> 
</body> 
</html> 

在代码隐藏

using System; 
using System.Collections.Generic; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.Services; 

public partial class ClearSessionOnPageUnload : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 
    [WebMethod] 
    public static void AbandonSession() 
    { 
     HttpContext.Current.Session.Abandon(); 
    } 

} 

您可以在AbandonSession方法把断点来验证这是在卸载击中。

1

你所试图做的是一个坏主意。考虑在会话中放置较少的数据,或者降低超时。

也许你没有意识到onunload在用户刷新或导航离开页面时触发。因此,假设你的代码实际工作,如果你用户刷新他们的页面,那么他们的会话将被终止。如果他们访问了该网站上的任何其他页面,他们的会话也将被终止!

可能不是您希望的功能!

0

没有办法一贯处理这种类型的事件。会话“结束”的原因太多了。其中最简单的是丢失或关闭的连接。在这种情况下,任何启动的JavaScript都将永远不会到达服务器。

即使你能按照你想要的方式工作,它只能在部分时间内工作。如果你不能依靠它,你的时间可能会花费和不同的解决方案。

0

已经有几年了,但我不知道WebMethod可以是静态的。