通过Global.asax文件里面的Session_End事件记录用户退出 (or session timeout)

Session.Abandon()和timeout会触发Global.asax的Session_End事件。可以通过这个事件来记录用户退出或者session timeout,这样每个用户都会有一条登陆和退出记录。

退出登陆调用方法:

public void PerformLogout()
{
    HttpContext.Current.Session["PerformLogout"] = true;
    HttpContext.Current.Session.Abandon();
}

Session_End事件代码:  

protected void Session_End(Object sender, EventArgs e)
{
    BusinessContext bizContext = (BusinessContext)Session["BusinessContext"];
    string loginID = string.IsNullOrEmpty(bizContext.LoginID) ? "" : bizContext.LoginID;
    string title = "Timeout";
    if (Convert.ToBoolean(Session["PerformLogout"]))
    {
        title = "Logout";
    }
    BusinessEvent.Log(BizLogCategory.SECURITY, BizLogModule.USER_AUTHENTICATION, title, "[PerformLogout]Logout Successfully", "LoginID: " + loginID, bizContext);
}

有如下几点需要注意:

1. 尽管我们先调用Session.Abandon(),但是在Session_End事件里还是可以继续访问所有session的值。正是因为这个,所以我们可以在PerformLogout方法中给Session["PerformLogout"]赋值,然后通过这个值来判断Session_End事件是由用户登出触发还是由session timeout触发。

2. ASP.NET里面Session和HttpContext.Current.Session对象都指向System.Web.SessionState.HttpSessionState,大部分地方这两个对象可以互换使用,但是在Session_End事件里,HttpContext.Current返回的是null,所以只能通过Session对象来访问session值。为什么要这样写,参考这里

3. 引起session timeout的设置比较多,测试过的有web.config里面的sessionState timeout, IIS Application Pools的Idle Time-out, IIS Application Pools Recycle, Stop website, 修改web.config等。

 

https://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionstatemodule.end(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.abandon(v=vs.110).aspx
http://forums.asp.net/t/1275683.aspx?Can+t+access+to+Session+variable+inside+Session_End+Event
http://stackoverflow.com/questions/940742/difference-between-session-and-httpcontext-current-session
http://stackoverflow.com/questions/27657773/why-is-httpcontext-current-null-during-the-session-end-event
http://stackoverflow.com/questions/19509672/why-is-httpcontext-current-null
http://stackoverflow.com/questions/12294532/asp-net-values-of-session-variables-in-session-end-event
https://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.abandon.aspx
https://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionstatemodule.end.aspx
http://stackoverflow.com/questions/13264212/on-session-timeout-capture-info
http://www.beansoftware.com/ASP.NET-Tutorials/Find-If-Session-Expired.aspx

posted @ 2016-04-26 17:14  liangzi4000  阅读(4655)  评论(0编辑  收藏  举报