在我的前一篇文章《妙用Cache检验用户是否重复登陆》,经过实践和思考,发现忽略了一个很重要的地方:只是在登陆时,设置了一次登录值到Cache中。如果Cache失效的时间设置久了,用户一旦退出,在较短的时间间隔内重新登陆时,会发现无法登陆。但是如果失效时间设置短了,恶意登陆者又会在较短的时间内重新登陆,而且成功通过检验。显然这种判断方法是不完善的。
我们需要怎么来改进这个时间的难题呢?设置一个较短的失效时间间隔,然后每隔一定时间,检查一下Cache,把用户登陆信息重新写入Cache。那么只要用户不退出网站系统,或者不关闭浏览器,这种判断方法将会一直有效!那么,在WEB上,在ASP.NET下,什么东西能方便的实现计时器的效果呢?目前而言,最好的选择无疑是 ATLAS 中的Timer控件!能够设置计时器的启动,间隔时间,以及间隔时间后做的事件。
程序改进以后,分享如下,请参看程序注释:
前台页面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="登陆" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Width="350px"></asp:Label>
<asp:Button ID="Button2" runat="server" Text="清除Cache" />
<asp:Timer ID="Timer1" runat="server" Enabled="False" Interval="15000" OnTick="Timer1_Tick">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
后台程序
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//用户名
string sName = TextBox1.Text;
//生成Key
string sKey = sName + "_Login";
//得到Cache中的给定Key的值
string sUser = Convert.ToString(Cache[sKey]);
//检查是否存在
if (sUser == null || sUser == String.Empty)
{
共有 0 位网友发表了评论,得分 0 分,平均 0 分 查看完整评论