很多时候我们只允许一个人账号同时只能在一个地方登录。特别是一些后台。避免产生一些数据错乱的问题。
比如同一个账号在两个地方同时登录同时操作的时候可能会产生数据冲突的问题。比如有一个账号登录的时候发现没有数据。
这个功能还是很多地方都有。当一个账号登录。然后再使用这个账号在其他地方登录。这个时候前面的登录就会提示在其他地方登录过,然后被注销掉登录。
//这里用的是Application 其实还可以使用其他的变量 比如缓存Cache 只要能够保证 甚至记录到数据库也可以 其实可以记录到静态变量 static也可以 public ActionResult Login() { var username = "user1"; var identity = Guid.NewGuid().ToString();//我们这里用guid 如果是session登录方式 大家可以用sessionid var dict = HttpContext.Application["loginuserguid"] as Dictionary<string, string>; if (dict==null) { dict = new Dictionary<string, string>(); } //处理登录 Session["CurrentUser"] = username; identity = HttpContext.Session.SessionID; if (dict.ContainsKey(username)) { dict[username]= identity; } else { dict.Add(username, identity); } HttpContext.Application["loginuserguid"] = dict;//记录到了全局的application //写会客户端的cookie 用session就不需要写cookie //var cookie = new HttpCookie("bamn"); //cookie.Value = identity; //HttpContext.Response.Cookies.Add(cookie); return View(); } public ActionResult Page() { //下面是要登录才能访问的功能 var username = "user1";//登录人的名称 var dict = HttpContext.Application["loginuserguid"] as Dictionary<string, string>; if (dict!=null) { //var identity = HttpContext.Request.Cookies["bamn"]; var identity = HttpContext.Session.SessionID; if (identity != null) { if (dict.ContainsKey(username)) { if (identity == dict[username]) { ViewBag.Message = "你是最后一个登录的人"; } else { ViewBag.Message = "你在别处已经登录过"; } } } } return View(); }