What is the difference between these two HttpConte

2019-01-25 03:33发布

What is the difference between these 2 piece of codes.

HttpContext.Current.Session["myvariable"]
Session["myvariable"]

asp.net 4.0 and C# 4.0

8条回答
冷血范
2楼-- · 2019-01-25 04:14

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."

查看更多
相关推荐>>
3楼-- · 2019-01-25 04:18

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.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-25 04:18

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 referencing HttpContext.Current.Session

查看更多
祖国的老花朵
5楼-- · 2019-01-25 04:27

There's no difference. They are the same thing; the second form is shorter :)

查看更多
forever°为你锁心
6楼-- · 2019-01-25 04:28

There is a difference. The second one (Session) is a property of many .NET objects, like Page 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).

查看更多
smile是对你的礼貌
7楼-- · 2019-01-25 04:28

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.

查看更多
登录 后发表回答