'我这里采取的是使用 Hashtable
'在.NET Framework中,Hashtable是System.Collections命名空间提供的一个容器,用于处理和表现类似key/value的键值对,其中key通常可用来快速查找(.NET对Hashtable优化,查询非常快),同时key是区分大小写和数据类型;value用于存储对应于key的值。Hashtable中key/value键值对均为object类型,所以Hashtable可以支持任何类型的key/value键值对.
'第一步:
' 在应用程序启动时运行的代码. 在 Global.asax Application_Start 创建 Hashtable
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) ' 在应用程序启动时运行的代码 ' 在启动时创建 Hashtable ,不需要数据库 Dim hTable As Hashtable = New Hashtable Application("UserSessionIdHashtable") = hTable '单个用户登录判断 Hashtable key=ID, value=sessionID End Sub
'第二步:
'在用户登录时候把 Session.SessionID 写入 Hashtable
Public Function UserLogin(ByVal UserName As String, ByVal UserPassword As String) As Byte '这里返回是否登陆成功,如 0 = 正常, 1 = 未激活用户, 2 = 用户锁定, 3 = 用户名密码错误 ...... dim LogonValue as integer = 3 '省略查询数据库和登陆判断代码,并设置 LogonID 值 If LogonValue = 0 '登录成功 Dim UserID As Integer = CInt(T.Rows(0).Item("ID")) '从上面的查询数据库获得用户ID, Dim hTable As Hashtable = CType(HttpContext.Current.Application("UserSessionIdHashtable"), Hashtable) '写Hashtable Dim HashtableKey As Integer = UserID 'Hashtable key ,这里使用用户ID,注意数据类型需要和以后查询的一致 Dim uSessionID As String = Trim(HttpContext.Current.Session.SessionID) 'Hashtable value ,这里是 SessionID If hTable.ContainsKey(HashtableKey) Then '判断Value是否存在 hTable(HashtableKey) = uSessionID 'Value存在>更新 Else hTable.Add(HashtableKey, uSessionID) 'Value不存在>添加 End If HttpContext.Current.Session("LogonUserID") = UserID '把用户ID放入Session End If Return LogonValue End Function
'第三步:
'判断用户登录是否正常
Public Function CheckLogin() As Byte '返回登录是否正常 '这里返回登录是否正常,如 0 = 正常, 1 = Session 超时 , 2 = 重复登录 ...... Dim CacheValue = 0 If HttpContext.Current.Session("LogonUserID") Is Nothing Then 'Session 不存在,登录超时 CacheValue = 1 Else Dim HashtableKey As Integer = As Integer = CInt(HttpContext.Current.Session("LogonUserID")) 'Hashtable key ,从Session获得用户ID Dim uSessionID As String = Trim(HttpContext.Current.Session.SessionID) 'Hashtable value ,这里是 SessionID Dim hTable As Hashtable = CType(HttpContext.Current.Application("UserSessionIdHashtable"), Hashtable) 'Hashtable If hTable.ContainsKey(HashtableKey) = False Then 'Value不存在,没有登录 CacheValue = 1 ElseIf hTable(HashtableKey).ToString().Equals(uSessionID) = False Then 'Value不一样,从其他浏览器或其他窗口登录 CacheValue = 2 End If End If Return CacheValue End Function
|