mvc 简单实现一个账号只能在一个地方登录

本文详细介绍了在MVC项目中如何通过Session管理实现用户在线状态的监测,包括Session_ID保持、在线用户记录更新及JS定时验证,确保同一账号在不同地点登录时前一用户能被强制下线。

1.在mvc项目中找到 Global.asax

//保证同一次会话的SessionID 不变

        protected void Session_Start(object sender, EventArgs e)
        { }

        protected void Session_End(object sender, EventArgs e)
        {
            Hashtable hOnline = (Hashtable)Application["Online"];
            if (hOnline != null)
            {
                if (hOnline[Session.SessionID] != null)
                {
                    hOnline.Remove(Session.SessionID);
                    Application.Lock();
                    Application["Online"] = hOnline;
                    Application.UnLock();
                }
            }
        }

2.在LoginController中找到你的Index方法

 HttpContext httpContext = System.Web.HttpContext.Current;
                    var userOnline = (Hashtable)httpContext.Application["Online"];//(Dictionary<string, string>)httpContext.Application["Online"];
                    if (userOnline != null)
                    {
                        IDictionaryEnumerator enumerator = userOnline.GetEnumerator();
                        while (enumerator.MoveNext())
                        {
                            if (enumerator.Value != null && enumerator.Value.ToString().Equals((acc.Code).ToString()))
                            {
                                userOnline[enumerator.Key.ToString()] = "_offline_";
                                break;
                            }
                        }

                    }

                    else
                    {
                        userOnline = new Hashtable();
                    }
                    userOnline[Session.SessionID] = acc.Code;//唯一的编号,账户编号
                    httpContext.Application.Lock();
                    httpContext.Application["Online"] = userOnline;
                    httpContext.Application.UnLock();

3.写JS  时刻验证是否有相同的ID

$(document).ready(function () {
    //定时检测是否被强制下线
    setInterval(function () {
        CheckIsForcedLogout();
    }, 5000);
});

//检测是否被强制下线
function CheckIsForcedLogout() {
    $.ajax({
        url: "/Login/CheckIsForcedLogout",
        type: "POST",
        dataType: "json",
        success: function (msg) {
            if (msg.OperateResult == "Success") {
                $.messager.alert('', msg.OperateData, 'error', function () {
                    window.location.href = "http://" + window.location.host + "/Login";
                   // window.location.href = "/Account/Login";
                });
            }
        },
        error: function (ex) { }
    });
}

4.在LoginContrcoller中写方法 CheckIsForcedLogout()主要是检查是否有相同的Id(账户编号)

        [HttpPost]
        public JsonResult CheckIsForcedLogout()
        {
            try
            {
                HttpContext httpContext = System.Web.HttpContext.Current;
                Hashtable userOnline = (Hashtable)httpContext.Application["Online"]; if (userOnline != null)
                {
                    if (userOnline.ContainsKey(httpContext.Session.SessionID))
                    {
                        var value = userOnline[httpContext.Session.SessionID];
                        //判断当前session保存的值是否为被注销值
                        if (value != null && "_offline_".Equals(value))
                        {
                            //验证被注销则清空session
                            userOnline.Remove(httpContext.Session.SessionID);
                            httpContext.Application.Lock();
                            httpContext.Application["online"] = userOnline;
                            httpContext.Application.UnLock();

                            string msg = "下线通知:当前账号另一地点登录, 您被迫下线。若非本人操作,您的登录密码很可能已经泄露,请及时改密。";

                            //登出,清除cookie
                            FormsAuthentication.SignOut();

                            return Json(new { OperateResult = "Success", OperateData = msg }, JsonRequestBehavior.AllowGet);
                        }
                    }
                }
                return Json(new { OperateResult = "Failed" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { OperateResult = "Failed" }, JsonRequestBehavior.AllowGet);
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值