应用场景:用户登录系统,如果该账号同时在别处登录了,前一个登录的用户就会被踢掉。
1、系统登录成功之后调用一个方法:
/// <summary>
/// 配置单用户登录
/// </summary>
/// <param name="Name"></param>
public void GetOnline(string Name)
{
Hashtable SingleOnline = (Hashtable)System.Web.HttpContext.Current.Application["Online"];
if (SingleOnline == null)
SingleOnline = new Hashtable();
//System.Web.HttpContext.Current.Session["onlyLogin"] = Name;
//SessionID
if (SingleOnline.ContainsKey(Name))
{
SingleOnline[Name] = System.Web.HttpContext.Current.Session.SessionID;
}
else
SingleOnline.Add(Name, System.Web.HttpContext.Current.Session.SessionID);
System.Web.HttpContext.Current.Application.Lock();
System.Web.HttpContext.Current.Application["Online"] = SingleOnline;
System.Web.HttpContext.Current.Application.UnLock();
}
2、重写一个过滤器:
/// <summary>
/// 重写定义过滤器方法;判断当前用户是否在别处登录。
/// </summary>
public class LoginActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Hashtable singleOnline = (Hashtable)filterContext.HttpContext.Application["Online"];
// 判断当前SessionID是否存在
if (singleOnline != null && singleOnline.ContainsKey(filterContext.HttpContext.User.Identity.Name))
{
if (!singleOnline[filterContext.HttpContext.User.Identity.Name].Equals(filterContext.HttpContext.Session.SessionID))
{
filterContext.Result = new ContentResult() { Content = "<script>alert('您的帐号已在别处登录 ,将被迫下线(请保管好自己的账号密码)!');" };
}
}
base.OnActionExecuting(filterContext);
}
};
3、在global.asax文件里面插入如下代码段:
/// <summary>
/// 在Session过期或者退出系统时释放资源。
/// </summary>
protected void Session_End()
{
Hashtable SingleOnline = (Hashtable)System.Web.HttpContext.Current.Application["Online"];
if (SingleOnline != null && SingleOnline[User.Identity.Name] != null)
{
SingleOnline.Remove(Session.SessionID);
System.Web.HttpContext.Current.Application.Lock();
System.Web.HttpContext.Current.Application["Online"] = SingleOnline;
System.Web.HttpContext.Current.Application.UnLock();
}
Session.Abandon();
}