Session和HttpContext.Current.Session之间的区别

时间:2009-06-02 17:14:28

标签: asp.net

Session和HttpContext.Current.Session对象有什么区别?

4 个答案:

答案 0 :(得分:104)

这里有点晚了,但这是我刚刚发现的东西。

@Phillipe Leybaert和@CSharpAtl都不正确。 HttpApplication的{​​{1}}属性表现出与属性Session不同的行为。他们将返回对同一HttpContext.Current.Session实例的引用,如果一个可用。当没有HttpSessionState的实例可用于当前请求时,它们的作用不同。

并非所有HttpSessionState都提供会话状态。为此,HttpHandler 必须实施[一个或两个?]标记接口HttpHandlerIRequiresSessionState

如果没有可用的会话,

IReadOnlySessionState只会返回HttpContext.Current.Session

nullHttpApplication属性的实现会引发Session消息HttpException,而不是返回Session state is not available in this context.引用。

不实现会话的null的一些示例是通常静态资源的默认处理程序,例如图像和CSS文件。在这种情况下(如HttpHandler事件处理程序中)对HttpApplication的{​​{1}}属性的任何引用都会导致Session被抛出。

不用说,意外的global.asax提供了WTF?!如果你没想到的那一刻。

HttpException类的HttpException属性因此实现(来自Reflector):

Session

答案 1 :(得分:8)

没有区别。

Page.Session的getter返回上下文会话。

答案 2 :(得分:2)

无。 Session只指向HttpContext.Current.Session

答案 3 :(得分:0)

在内部,Page.Session仅指向它是HttpContext.Current.Session,但根据调用位置的不同,仍然存在两个差异。

Page.Session只能从从System.Web.UI.Page继承的类访问,从WebMethod访问时它将抛出HttpException。
HttpContext.Current.Session可以从任何地方访问,只要您正在Web应用程序的上下文中运行。


您可以访问Page.Session但不能访问HttpContext.Current.Session的其他重要区别:

如果您的页面中有一个名为GetData的方法(从System.Web.UI.Page继承),则该方法是与其他页面方法在不同线程中并发执行的GetData方法可以访问Page.Seession,但不能访问HttpContext.Current.Session。

因为从不同的线程调用了GetData,所以HttpContext.Current为null,而HttpContext.Current.Session将抛出空引用异常,但是Page.Session仍将与页面对象一起附加,因此页面方法GetData可以访问Page.Session。