What is the difference between these 2 piece of codes.
HttpContext.Current.Session["myvariable"]
Session["myvariable"]
asp.net 4.0 and C# 4.0
What is the difference between these 2 piece of codes.
HttpContext.Current.Session["myvariable"]
Session["myvariable"]
asp.net 4.0 and C# 4.0
Another pretty thorough answer from Nicholas Carey https://stackoverflow.com/a/6021261/365017
"HttpApplication's Session property exhibits different behaviour than does that of the proporty 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 HttpHandlers 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 return a null reference."
On a stantard scenario they are the same. The difference is that the first statement will also work in static contexts such as a WebMethod.
There is no difference. Page.Session returns the
HttpContext.Current.Session
With that being said, I've written .dll's that act as extensions for web applications. These .dll's have not concept of
Session
. In these instances, I can access the current session of the web application that is using my .dll by referencingHttpContext.Current.Session
There's no difference. They are the same thing; the second form is shorter :)
There is a difference. The second one (
Session
) is a property of many .NET objects, likePage
for example. So, you can't have access to it, in the constructor of those objects for example. However, the first one (HttpContext.Current.Session
), is always ready and at your disposal (of course, after the session is loaded in the Request Processing Pipeline).There is no difference in behavior. If you are using code in your custom class where HttpContext is not directly available and want to access session value than we use first line of code, while second line is used when accessing in Page or control classes.