第二:修改web.
private void isLo
gin()
{
Hashtable h = (Hashtable)Application["online"];
if (h
== null)
{
h = new Hashtable();
}
//验证用户是否在Application中存在(是否在线)
IDictionaryEnumerator e1 = h.GetEnumerator();
bool flag = false;
while (e1.MoveNext())
{
if (checkCookie(e1.Value.ToString()))
{
flag = true;
break;
}
}
if (flag)
{
Response.Wr
ITe("<script defer language='javascript'>alert('This user is online!');history.go(-1);</script>");
}
else
{
LOGinLogic login = new loginLogic(this.txt_user_id.Text.Trim(), this.txt_password.Text.Trim());
if (!login.getLoginStatus)
{
Response.Write("<script defer language='javascript'>alert('Invalid UserID or password.Please try ag
ain.');</script>");
}
else
{
//生成服务端标识值
DateTime now = DateTime.Now;
string cookieValue = now.Year.ToString() + now.Month.ToString() + now.Day.ToString() + now.Hour.ToString() + now.Minute.ToString() + now.Second.ToString() + now.Millisecond.ToString();
//把userid + 标识值写入全局变量表
h[Session.SessionID] = this.txt_user_id.Text.Trim() + "-" + cookieValue;
Application["Online"] = h;
//把标识值写入客户端cookie
Response.Cookies["hqs"].Value =cookieValue;
Response.Cookies["hqs"].E
xpires = DateTime.Now.AddDays(1);
//用户信息记入session
Session["userid"] = this.txt_user_id.Text.Trim();
Response.
redirect("Manage/index.aspx");
}
}
}
private bool checkCookie(string ap
pvalue)
{
bool isExist = false;
if (Request.Cookies["hqs"] != null)
{
string cookieValue = Request.Cookies["hqs"].Value;
char[] sp = new char[1]{'-'};
string appUserid = appValue.Split(sp)[0].ToString();
string appCookie = appValue.Split(sp)[1].ToString();
if (appUserid == this.txt_user_id.Text.Trim()
&& appCookie != cookieValue)
isExist = true;
}
return isExist;
}
中测试可能有问题,还在放在IIS的正式环境中去测试.
关于此方案的说明:一般情况下session 的timeout时间为20分钟,也就是说,如果这个用户直接关掉浏览器,然后马上再登录,这个时间session还没有到期,所有不会触发global.asax中的session_end事件,所以会提示这个用户还在线,20分钟后这个事件执行过后,会删掉这个不
续上篇,现在有新的问题了,如果用户非正常退出那么,session在20分钟内不会执行END事件,也就是说用户还是在线状态,那么此用户再次登录将不被允许。这显然有点不合理。这个方案就显得不够完美了,希望大家补充。
Cache的功能,我们把用户的登录信息保存在Cache中,并设置过期时间为Session失效的时间,因此,一旦Session失效,我们的Cache也过期;而Cache对所有的用户都可以访问,因此,用它保存用户信息比数据库来得方便。
string sKey = usern
ame.Text.ToString().Trim(); // 得到Cache中的给定Key的值
string
SUSEr = Convert.ToString(Cache[sKey]); // 检查是否存在
if (sUser == null || sUser == String.Empty)
{
TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.
current.Session.Timeout, 0, 0);//取得Session的过期时间
HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.Cach
eitemPriority.NotRemovable, null);//将值放入cache己方便单点登录
//成功登录
}
else if (Cache[sKey].ToString() == sKey)//如果这个
账号已经登录
{
ClientScript.RegisterStartupScript(GetTy
PE(), "提示", "<script>alert('对不起,当前用户已经登录');</script>");
return;
}
else
{
Session.Abandon();//这段主要是为了避免不必要的错误导致不能登录
}