Calling a Page Method when the Browser Closes

2019-02-21 00:16发布

问题:

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

回答1:

I have tested with below code and it is working fine.

In Aspx page

<!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>

In Codebehind

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();
    }

}

You can put breakpoint at AbandonSession method to verify that it is getting hit at unload.



回答2:

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!



回答3:

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.



回答4:

It's been a few years, but I didnt know WebMethod can be static.