用户登录成功后,将用户登录信息存放到Hashtable类型的Application["Online"]里面,其键值为 SessionID,其Value值为用户ID;当用户注销时,调用Session.Abandon;在Global.asax里面的 SessionEnd事件中,将用户ID从Hashtable中删除;在用户访问页面时,察看Hashtable中能不能 有对应的用户ID如果没有则判断用户不在线
1、公用类中判断用户能不能 在线的函数(供用户调用)
代码
/**/
///
<summary>
/// 判断用户strUserID能不能 包含在Hashtable h中
/// </summary>
/// <param name="strUserID"></param>
/// <param name="h"></param>
/// <returns></returns>
public static bool AmIOnline( string strUserName, Hashtable h)
{
if (strUserName == null )
return false ;
// 继续判断能不能 该用户已经登陆
if (h == null )
return false ;
// 判断哈希表中能不能 有该用户
IDictionaryEnumerator e1 = h.GetEnumerator();
bool flag = false ;
while (e1.MoveNext())
{
if (e1.Value.ToString().CompareTo(strUserName) == 0 )
{
flag = true ;
break ;
}
}
return flag;
}
/// 判断用户strUserID能不能 包含在Hashtable h中
/// </summary>
/// <param name="strUserID"></param>
/// <param name="h"></param>
/// <returns></returns>
public static bool AmIOnline( string strUserName, Hashtable h)
{
if (strUserName == null )
return false ;
// 继续判断能不能 该用户已经登陆
if (h == null )
return false ;
// 判断哈希表中能不能 有该用户
IDictionaryEnumerator e1 = h.GetEnumerator();
bool flag = false ;
while (e1.MoveNext())
{
if (e1.Value.ToString().CompareTo(strUserName) == 0 )
{
flag = true ;
break ;
}
}
return flag;
}
2、用户登录事件处理:
代码
private
void
btnlogin_Click(
object
sender, System.Web.UI.ImageClickEventArgs e)
{
// User为自定义的类,其中包含Login要领
User CurUser = new User();
CurUser.UserName = this .username.Text.Trim();
if (MyUtility.AmIOnline(CurUser.UserName, (Hashtable) Application[ " Online " ]))
{
response.write( " <script>alert('您所运用 的登录ID已经在线了!您不能重复登录!');</script> " );
return ;
}
else
{
Hashtable h = (Hashtable) Application[ " Online " ];
if (h == null )
h = new Hashtable();
h[Session.SessionID] = CurUser.UserName;
Application[ " Online " ] = h;
}
}
{
// User为自定义的类,其中包含Login要领
User CurUser = new User();
CurUser.UserName = this .username.Text.Trim();
if (MyUtility.AmIOnline(CurUser.UserName, (Hashtable) Application[ " Online " ]))
{
response.write( " <script>alert('您所运用 的登录ID已经在线了!您不能重复登录!');</script> " );
return ;
}
else
{
Hashtable h = (Hashtable) Application[ " Online " ];
if (h == null )
h = new Hashtable();
h[Session.SessionID] = CurUser.UserName;
Application[ " Online " ] = h;
}
}
代码
protected
void
Session_End(Object sender, EventArgs e)
{
Hashtable h = (Hashtable) Application[ " Online " ];
if (h[Session.SessionID] != null )
h.Remove(Session.SessionID);
Application[ " Online " ] = h;
}
{
Hashtable h = (Hashtable) Application[ " Online " ];
if (h[Session.SessionID] != null )
h.Remove(Session.SessionID);
Application[ " Online " ] = h;
}
根据网上资料提纯了一下、关键是思路!