ASP.net MVC实现单点登录

ASP.net MVC实现单点登录

单点登录效果:同一个账号在不同设备登录时,后登录的设备将前面登录的设备账号挤下线。
ASP.net MVC实现单点登录_第1张图片

1.登录时在服务器保存登录数据

Name是用户的一个唯一标识

  private void GetOnline(string Name)
  {
      Hashtable SingleOnline = (Hashtable)System.Web.HttpContext.Current.Application["Online"];
      if (SingleOnline == null)
      {
          SingleOnline = new Hashtable();
      }
      if (SingleOnline.ContainsKey(Name))
      {
          SingleOnline[Name] = Session.SessionID;
      }
      else
      {
          SingleOnline.Add(Name, Session.SessionID);
      }
      Session["user"] = Name;
      System.Web.HttpContext.Current.Application.Lock();
      System.Web.HttpContext.Current.Application["Online"] = SingleOnline;
      System.Web.HttpContext.Current.Application.UnLock();
  }

2.全局过滤请求判断当前账号是否在其它地方登录

APP_Start 下新建 FilterConfig.cs
排除部分请求(如登录请求不需要进行过滤拦截)

 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new LoginFilterAttribute() { IsCheck = true });
}

在不需要过滤的Action前加上以下代码

[LoginFilter(IsCheck = false)]

过滤验证

public bool IsCheck { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (!IsCheck)
    {
        return;
    }
    string ss = filterContext.HttpContext.Session["user"] as string;
    if (ss == null || ss == "")
    {
        filterContext.Result = new ContentResult() { Content = "" };
        return;
    }
    Hashtable singleOnline = (Hashtable)filterContext.HttpContext.Application["Online"];
    // 判断当前SessionID是否存在
    if (singleOnline != null && singleOnline.ContainsKey(ss))
    {
        if (!singleOnline[ss].Equals(filterContext.HttpContext.Session.SessionID))
        {
            filterContext.Result = new ContentResult() { Content = "" };
        }
    }
    base.OnActionExecuting(filterContext);
    Hashtable hOnline = (Hashtable)HttpContext.Current.Application["Online"];
    if (hOnline != null)
    {
        IDictionaryEnumerator idE = hOnline.GetEnumerator();
        while (idE.MoveNext())
        {
            if (idE.Key != null && idE.Key.ToString().Equals(HttpContext.Current.Session.SessionID))
            {
                //already login  
                if (idE.Value != null && "XXXXXX".Equals(idE.Value.ToString()))
                {
                    hOnline.Remove(HttpContext.Current.Session.SessionID);
                    HttpContext.Current.Application.Lock();
                    HttpContext.Current.Application["Online"] = hOnline;
                    HttpContext.Current.Application.UnLock();
                    filterContext.Result = new ContentResult()
                    {
                        Content = ""
                    };
                }
                break;
            }
        }
    }
    base.OnActionExecuting(filterContext);
}

你可能感兴趣的:(MVC)