2009-07-07 66 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可以是靜態的。