Search code examples
asp.net-mvcasp.net-membershipsession-statemembership-providerhttpcontext

Access Membership User On Session End


I'm currently trying to write a little bit of code to do some tidying up once a user abandons their session (either via time out or logging out) however would like to access the User object so I know who the session belongs to.

Unfortunately HttpContext is null so I can't access HttpContext.User or HttpContext.User.IsInRole or even the auth cookie directly. I understand the reasons behind this but wonder if there is there any other way to get access to this information when a session times out?

That is apart from the obvious answer of duplicating some of the information in the session.

Thanks.


Solution

  • You can use Global.asax's Session_End event. Session_End event is called automatically when a Session expired.

    The problem is Session_End event is called without a current request. As the result, HttpContext.Current is null inside Session_End.

    If you want to get user's information, you will need to save them inside Session as soon as user successfully logins.

    private void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set 
        // to StateServer or SQLServer, the event is not raised.
    
        var userName = Session["UserName"];
        var sessionId = Session.SessionID;
    }
    

    enter image description here