What is the difference between Session and HttpContext.Current.Session object?
An ASP.NET application that has session state enabled. A Web Forms page class that has access to the Page. Session property, or any class that has access to the HttpContext.
Item” data is live for single HTTP request/Response where HttpContext. Current. Session data is live throughout user's session.
HttpContext is an object that wraps all http related information into one place. HttpContext. Current is a context that has been created during the active request. Here is the list of some data that you can obtain from it.
Session will never be null if you have any variable in the Session. HttpContext. Current. Session represents a collection of all the session values that you are storing in the session.
A little late here, but here's something I just discovered.
@Phillipe Leybaert and @CSharpAtl are both incorrect. HttpApplication
's Session
property exhibits different behaviour than does that of the property HttpContext.Current.Session
. They will both return a reference to the same HttpSessionState
instance if one is available. They differ in what they do when there is no instance of HttpSessionState
available for the current request.
Not all HttpHandler
s provide session state. To do so, the HttpHandler
must implement [one or both?] the marker interfaces IRequiresSessionState
or IReadOnlySessionState
.
HttpContext.Current.Session
simply returns null
if there is no session available.
The HttpApplication
's implementation of the Session
property throws an HttpException
with the message Session state is not available in this context.
rather than returning a null
reference.
Some examples of HttpHandler
that do not implement session are the default handlers for normally static resources, such as image and CSS files. Any reference to the HttpApplication
's Session
property in such cases (as in global.asax
event handlers) will result an HttpException
being thrown.
Needless to say, the unexpected HttpException
provides a WTF?! moment if you're not expecting it.
The Session
property of the HttpApplication
class is implemented thus (from Reflector):
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public HttpSessionState Session { get { HttpSessionState session = null; if (this._session != null) { session = this._session; } else if (this._context != null) { session = this._context.Session; } if (session == null) { throw new HttpException(SR.GetString("Session_not_available")); } return session; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With