标签:
/// <summary>
/// 判断该用户是否在线cache
/// </summary>
/// <param name="userName">用户名</param>
public void ValidateUser(string userName)
{
string sKey = userName + "~" + System.Guid.NewGuid().ToString("N");
Response.Cookies["userName"].Value = sKey;//在客户端写入标识
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
//string cookieInfo = Request.Cookies["userName"].Value;
IDictionaryEnumerator CacheEnum = Cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
if (CacheEnum.Key.ToString().Split(‘~‘)[0] == sKey.Split(‘~‘)[0] &&
CacheEnum.Key.ToString().Split(‘~‘)[1] != sKey.Split(‘~‘)[1])
{
//如果找到匹配,删除缓存重新插入新的缓存
Cache.Remove(CacheEnum.Key.ToString());
}
}
//找不到用户名相等的就注册缓存
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.CacheItemPriority.NotRemovable, null);//将值放入cache己方便单点登录
//成功登录
//注意skey 是从cache中拿到的与当前用户名比对成功后才去比对guid
//当服务器端的guid与本机cookie guid 比较不通过,就证明后者登陆了。你就重新登陆吧
//return true;
}
继承System.Web.UI.Page
protected override void OnPreInit(EventArgs e)
{
//当session 失效了就重新登陆
if (HttpContext.Current.Session["userName"] == null)
{
HttpContext.Current.Response.Write("<script>window.parent.location.href=‘../../login.aspx‘</script>");
Response.End();
}
//与cache比对 拿服务器的标识与客户端的比对
string cookieInfo = Request.Cookies["userName"].Value;
IDictionaryEnumerator CacheEnum = Cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
if (CacheEnum.Key.ToString().Split(‘~‘)[0] == cookieInfo.Split(‘~‘)[0] &&
CacheEnum.Key.ToString().Split(‘~‘)[1] != cookieInfo.Split(‘~‘)[1])
{
//当用户名相同,guid不同就说明有人重登录了
HttpContext.Current.Response.Redirect("logincache.aspx");
}
}
base.OnPreInit(e);
}
标签:
原文地址:http://www.cnblogs.com/jinhaoObject/p/4535823.html