如何清除asp.net中的所有活动会话

时间:2017-07-06 14:22:07

标签: asp.net session

1)我想知道如何清除asp.net中的所有会话,以便每个登录系统的用户都可以工作,除非他们再次登录。

2)有没有办法遍历所有会话,为会话中存储的管理员用户制作例外?

提前致谢!

问候。

1 个答案:

答案 0 :(得分:0)

您不能从另一个会话中访问会话状态,但是可以通过“应用程序”状态共享数据,并在其他会话下次通过Global.asax发出请求时使用该数据杀死其他会话。

在Global.asax中通过Session_Start跟踪每个会话的启动时间

void Session_Start(object sender, EventArgs e)
{
    // Code that runs when a new session is started
    Session["dtmStart"] = DateTime.Now;
}

下次在Global.asax中通过Application_AcquireRequestState请求如果会话在应用程序状态下存储的当前终止时间之前启动的情况下,放弃每个会话

void Application_AcquireRequestState(object sender, EventArgs e)
{
    // Occurs as the first event in the HTTP pipeline chain of execution when ASP.NET responds to a request.

    // Check if session should be killed
    if (Application["dtmClearSessions"] != null 
        && Session["dtmStart"] != null
        && (DateTime)Application["dtmClearSessions"] > (DateTime)Session["dtmStart"])
    {
        // Check if user is an administator
        if (Application["lstAdminUserIds"] != null && Session["intMyUserId"] != null)
        {
            List<int> lstAdminUserIds = (List<int>)Application["lstAdminUserIds"];
            int intMyUserId = (int)Session["intMyUserId"];
            if (lstAdminUserIds.Contains(intMyUserId))
                return;
        }

        Session.Abandon();
    }
}

要标记应放弃会话,只需简单地设置Application["dtmClearSessions"] = DateTime.Now;,例如通过在页面上按按钮即可。

protected void btnKillEmAll_Click(object sender, EventArgs e)
{
    try
    {
        Application["dtmClearSessions"] = DateTime.Now;
    }
    catch (ThreadAbortException ex) { throw ex; }
    catch (Exception ex)
    {
        // TODO: RecordError(ex, "my_page.btnKillEmAll_Click", Request);
        // TODO: show error on screen litError.Text = ex.Message;
    }
}
相关问题