marvelTracker
marvelTracker

Reputation: 4969

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; }
    }

Upvotes: 3

Views: 2048

Answers (2)

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

what you have done is correct the session variable you have create will be available for all the request following the one that creates it. The HttpContext is one of the largest object you will find in web development and behind the scene is does lots of stuff. The reason why you don’t lose the session between the requests is because the server will keep it alive. You will be surprised to know that behind the scene the session uses the particular section of the cache

Upvotes: 1

Davide Piras
Davide Piras

Reputation: 44595

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.

Upvotes: 4

Related Questions