Search code examples
asp.net-mvc-3session-statesession-variables

HttpContext.Current.Session is Confused in Asp.net MVC 3.0


I'm working with an ASP.net MVC3.0 application and I keep Current User information in the Session of Current HttpContext.

As I know HttpContext.Current is for per current request.Therefore, my Session data should clear after the new request.However, I can receive Current User session data from request to request by storing HttpContext.Current. I did this sample for testing purpose to understand the session management in MVC 3.0.

My question: How I receive session data after current request ? I really appreciate your help.

public static UserAccountDto CurrentUser
    {
        get
        {
            if (HttpContext.Current == null)
                return null;

            if (HttpContext.Current.Session[CurrentUserSessionVariable] != null)
                return HttpContext.Current.Session[CurrentUserSessionVariable] as UserAccountDto;

            return null;
        }

        private set { HttpContext.Current.Session[CurrentUserSessionVariable] = value; }
    }

Solution

  • HttpContext.Current is not the same as:

    HttpContext.Current.Request
    

    the last one is different at every request, the first one contains members like User, Session, Server etc that are in many (but not all) cases the same request after request.