我已经用下面的代码进行了测试,它工作正常。
在 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 方法中放置断点,以验证它是否在卸载时被命中。