使用Ajax轮询检测当前会话状态
以下是代码示例:
首先,您需要添加一个名为"CheckSessionState"的Web服务,用于检测会话状态。示例代码如下:
[WebMethod(EnableSession = true)] public static bool CheckSessionState() { return HttpContext.Current.Session != null && HttpContext.Current.Session["UserId"] != null; }
接下来,您可以使用Ajax轮询调用此Web服务检查会话状态。示例代码如下:
function CheckSessionState() { var isSessionExpired = true; // Assume session is expired by default
$.ajax({
type: "POST",
url: "/your-app-path/CheckSessionState.asmx/CheckSessionState",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d) {
isSessionExpired = false; // Session is active
}
},
async: false // Make sure the function waits for the response before returning
});
return isSessionExpired;
}
最后,您可以在页面中定期调用此函数来检查会话状态。示例代码如下:
window.setInterval(function () { if (CheckSessionState()) { // Redirect to login page or show a message alert("Your session has expired. Please log in again."); window.location.href = "/your-app-path/login.aspx"; // Redirect to login page } }, 5000); // Check the session state every 5 seconds (adjust as needed)