private void GetOnline(string Name)
Hashtable SingleOnline = (Hashtable)System.Web.HttpContext.Current.Application["Online"];
if (SingleOnline == null)
SingleOnline = new Hashtable();
//Session["mySession"] = "Test";
//SessionID
if (SingleOnline.ContainsKey(Name))
SingleOnline[Name] = Session.SessionID;
SingleOnline.Add(Name, Session.SessionID);
var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
var Expires = DateTime.Now.AddMinutes(30);
httpCookie.Expires = Expires;
httpCookie.Value = FormsAuthentication.Encrypt(new FormsAuthenticationTicket(0, Name, DateTime.Now, Expires, false, Name));
HttpContext.Response.Cookies.Add(httpCookie);
System.Web.HttpContext.Current.Application.Lock();
System.Web.HttpContext.Current.Application["Online"] = SingleOnline;
System.Web.HttpContext.Current.Application.UnLock();
第二步 配置添加票证 和web.config
var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
var Expires = DateTime.Now.AddMinutes(30);
httpCookie.Expires = Expires;
httpCookie.Value = FormsAuthentication.Encrypt(new FormsAuthenticationTicket(0, Name, DateTime.Now, Expires, false, Name));
HttpContext.Response.Cookies.Add(httpCookie);
身份票证可以放到底层封装起来 用于存储用用户名和票证信息
添加完票证信息后 可能会出现User.Identity.Name 无法获取到值的问题,这个时候 就说明你web.config中未配置相应的参数
配置如下 在 <system.web>节点下配置 如下即可
<authentication mode="Forms">
<forms loginUrl="/" timeout="30" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
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>if(confirm('你的账号已在别处登陆,是否返回登陆页面重新登陆?')){window.location.href='/';}else{window.close();}</script>" };
base.OnActionExecuting(filterContext);
将这串代码引入你的过滤类中即可 然后就OK了 该过滤器用于判断是否存在重复登录的情况,过滤器怎么用这里就不多说了,若存在重复登录,则执行if语句内的处理方式,这里的处理方式是弹出个确认框,当然你也可以直接跳转到登录地址,看需要更改。
第四步 就是解决 资源释放问题 将如下代码放入 Global.asax 全局配置文件中
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();