解决重复登录 用到了 .net 身份票证 和Global全局处理文件
第一步 登录方法 传入用户名
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;
???????????}
???????????else
???????????????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>
第三步 新建一个类配置mvc的过滤类
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语句内的处理方式,这里的处理方式是弹出个确认框,当然你也可以直接跳转到登录地址,看需要更改。
ASP.NET ?解决账号重复登录问题
原文地址:https://www.cnblogs.com/cenwenlin/p/9105143.html