65.9K
CodeProject 正在变化。 阅读更多。
Home

在 ASP.NET 中使用 jQuery 实现会话超时警告消息

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.95/5 (26投票s)

2014 年 1 月 15 日

CPOL

3分钟阅读

viewsIcon

127326

downloadIcon

3392

如何在会话超时前 15 分钟向用户显示警告消息,换句话说,如果用户空闲时间超过 5 分钟,则在浏览器中显示一条消息

引言

在本文中,我们将研究如何在会话超时前 15 分钟向用户显示警告消息,换句话说,如果用户空闲时间超过 5 分钟,则在浏览器中显示一条消息。

什么是会话?

当我们在计算机上使用应用程序时,我们会遵循一些步骤,例如打开一个应用程序,进行一些更改然后关闭它。这些步骤很像一个会话,因为用户和计算机之间存在交互,因此计算机知道用户是谁。它知道我们对应用程序所做的一切。但是,在互联网上存在一个问题:Web 服务器不知道用户是谁以及他做了什么,因为 Web 是无状态的,这意味着每次页面发布到服务器时,都会重新创建 Web 页面类的新实例。换句话说,可以说 HTTP 是一种无状态协议,它不会在页面中保存用户/客户端信息。

会话数据是基于每个客户端存储的;换句话说,对于每个客户端,会话数据都是单独存储的。会话提供了在服务器内存中存储信息的能力,并且可以为任何页面检索该信息。

使用 jQuery 创建会话超时警告消息的步骤

使用 jQuery

我们需要在网页上添加一个 JavaScript js 文件引用,以便我们可以检索网页上的 JavaScript 函数,以便在会话超时之前收到消息。所以我们首先加载 jQuery。

<script src="jquery/js/jquery-1.8.3.js" type="text/javascript"></script> 

变量声明

我们需要声明一些全局变量;这些变量用于计算用户的空闲时间和会话时间。

//How frequently to check for session expiration in milliseconds
var sess_pollInterval = 60000;
//How many minutes the session is valid for
var sess_expirationMinutes = 20;
//How many minutes before the warning prompt

var sess_warningMinutes = 5;
var sess_intervalID;
var sess_lastActivity; 

会话初始化

我们需要创建一个 JavaScript 函数,在页面加载时初始化会话时间。在这里,我们使用 sess_lastActivity 变量来存储页面加载的时间,然后我们设置会话间隔。 

function initSession()
{  
    sess_lastActivity = new Date();
    sessSetInterval();
    $(document).bind('keypress.session', function (ed, e)
    {
        sessKeyPressed(ed, e);

    });
} 

会话间隔和警告消息

我们创建两个函数;一个用于设置会话间隔,另一个用于计算会话间隔,并在会话超时时显示消息。

 function sessSetInterval()
{
    sess_intervalID = setInterval('sessInterval()', sess_pollInterval);
}
function sessInterval()
{
        var now = new Date();
        //get milliseconds of differences
        var diff = now - sess_lastActivity;
        //get minutes between differences

        var diffMins = (diff / 1000 / 60); 
        if (diffMins >= sess_warningMinutes)
        {
            //warn before expiring

            //stop the timer
            sessClearInterval();
            //prompt for attention
            var active = confirm('Your session will expire in ' + (sess_expirationMinutes - sess_warningMinutes) +
                ' minutes (as of ' + now.toTimeString() + '), press OK to remain logged in ' +
                'or press Cancel to log off. \nIf you are logged off any changes will be lost.');
            if (active == true)
            {
                now = new Date(); 

              diff = now - sess_lastActivity;
                diffMins = (diff / 1000 / 60);
                if (diffMins > sess_expirationMinutes)
                {
                    sessLogOut();
                }
                else
                {
                    initSession();
                    sessSetInterval();
                    sess_lastActivity = new Date();
                }
            }
            else
            {
                sessLogOut();
            }
        }
    } 

Logout

当用户空闲时间超过 5 分钟时,我们会收到来自系统的注意消息,并且每当我们单击“取消”按钮时,我们都会移动到注销页面。从消息窗口打开的时间算起,15 分钟后,我们单击“确定”按钮,然后也移动到注销页面。因此,我们创建一个注销函数,它是

 function sessLogOut()
    {
        window.location.href = 'Logout.aspx';
    }  

Using the Code

目录结构

下图显示了 Web 窗体和 js 文件所在的目录结构。

Directory Structure

图 1.1 应用程序的目录结构

完整代码

 <%@ Page Language="C#" AutoEventWireup="true" 
 CodeBehind="SessionInjQuery.aspx.cs" Inherits="JQueryExample.SessionInjQuery" %>
<!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 src="jquery/js/jquery-1.8.3.js" type="text/javascript"></script> 
    <script type="text/javascript">
        var sess_pollInterval = 60000;
        var sess_expirationMinutes = 20;
        var sess_warningMinutes = 5;
        var sess_intervalID;
        var sess_lastActivity;

        function initSession() {
            sess_lastActivity = new Date();
            sessSetInterval();
            $(document).bind('keypress.session', function (ed, e) {
                sessKeyPressed(ed, e);
            });
        }
        function sessSetInterval() {
            sess_intervalID = setInterval('sessInterval()', sess_pollInterval);
        }
        function sessClearInterval() {
            clearInterval(sess_intervalID);

        }
        function sessKeyPressed(ed, e) {
            sess_lastActivity = new Date();
        }
        function sessLogOut() {
            window.location.href = 'Logout.aspx';
        }
        function sessInterval() {
            var now = new Date();
            //get milliseconds of differneces
            var diff = now - sess_lastActivity;
            //get minutes between differences
            var diffMins = (diff / 1000 / 60);
            if (diffMins >= sess_warningMinutes) {
                //warn before expiring
                //stop the timer
                sessClearInterval();
                //prompt for attention
                var active = confirm('Your session will expire in ' + 
                (sess_expirationMinutes - sess_warningMinutes) +
                ' minutes (as of ' + now.toTimeString() + '), 
                press OK to remain logged in ' +
                'or press Cancel to log off. 
                \nIf you are logged off any changes will be lost.');
                if (active == true) {

                    now = new Date();
                    diff = now - sess_lastActivity;
                    diffMins = (diff / 1000 / 60);
                    if (diffMins > sess_expirationMinutes) {
                        sessLogOut();
                    }
                    else {
                        initSession();
                        sessSetInterval();
                        sess_lastActivity = new Date();
                    }
                }
                else {
                    sessLogOut();
                }
            }
        }
        
</script>
 
</head>
<body onload="initSession()">
    <form id="form1" runat="server">
    <div>
     <h1>Your Most Welcome!</h1>
    </div>
    </form>
</body>
</html> 

警告消息

Warning message in jQuery

图 1.2 警告消息

在警告消息中,我们有两个按钮,一个是“确定”,另一个是“取消”按钮。当我们在浏览器中显示警告消息之前的 15 分钟内单击“确定”按钮时,会话时间间隔将被重置,但是当我们在警告消息之后的 15 分钟后单击“确定”按钮时,我们会移动到注销页面。每当我们单击“取消”按钮时,我们也会移动到注销页面。

Logout from Application

图 1.3 会话过期 
 
© . All rights reserved.