Asp.net 会话和HttpContext.Current.Session之间的差异
会话和HttpContext.Current.Session对象之间有什么区别?没有区别Asp.net 会话和HttpContext.Current.Session之间的差异,asp.net,Asp.net,会话和HttpContext.Current.Session对象之间有什么区别?没有区别 Page.Session的getter返回上下文会话。无Session只是指向了HttpContext.Current.Session这里有点晚了,但我刚刚发现了一些东西 @Phillipe Leybaert和@CSharpAtl都不正确HttpApplication的会话属性表现出与属性HttpContext.Current.Session不同的行为。如果有一个实例可用,它们都将返回对相同的HttpSes
Page.Session的getter返回上下文会话。无
Session
只是指向了HttpContext.Current.Session
这里有点晚了,但我刚刚发现了一些东西
@Phillipe Leybaert和@CSharpAtl都不正确HttpApplication
的会话
属性表现出与属性HttpContext.Current.Session
不同的行为。如果有一个实例可用,它们都将返回对相同的HttpSessionState
实例的引用。当当前请求没有可用的HttpSessionState
实例时,它们的操作有所不同
并非所有的HttpHandler
s都提供会话状态。为此,HttpHandler
必须实现[一个或两个?]标记接口irerequiressessionstate
或IReadOnlySessionState
HttpContext.Current.Session
如果没有可用的会话,只返回null
HttpApplication
对Session
属性的实现会抛出一个HttpException
,其中消息Session state在此上下文中不可用。
而不是返回一个null
引用
一些未实现会话的HttpHandler
示例是通常静态资源(如图像和CSS文件)的默认处理程序。在这种情况下(如在global.asax
事件处理程序中),对HttpApplication
的Session
属性的任何引用都将导致抛出HttpException
不用说,意外的HttpException
提供了一个WTF?!如果你没有预料到的话,请等一下
HttpApplication
类的Session
属性由此实现(从Reflector):
在内部,Page.Session只指向它的HttpContext.Current.Session,但根据调用它的位置,仍然有两个不同之处
只能从继承自System.Web.UI.Page的类访问Page.Session,从WebMethod访问时,它将引发HttpException。其中,只要您在Web应用程序的上下文中运行,就可以从任何位置访问as HttpContext.Current.Session
您可以访问Page.Session但无法访问HttpContext.Current.Session的其他重要区别:
如果您的页面中有一个名为GetData的方法(从System.Web.UI.Page继承而来),该方法在与其他页面方法不同的线程中并发执行,则GetData方法可以访问该页面。请参阅会话,但您无法访问HttpContext.Current.Session
这是因为GetData是从不同的线程调用的,所以HttpContext.Current为null,HttpContext.Current.Session将引发null引用异常,但Page.Session仍将附加Page对象,因此Page方法GetData可以访问Page.Session。当您说“Session”时,需要澄清的是,您指的是System.Web.UI.Page.Session。会话对象可在ASP.NET页面的上下文中使用。感谢您为填写更好的答案而付出的努力。没问题。我刚刚经历了一场相当恼人的WTF?那个花了一些时间整理的时刻。我想我应该把它记录下来,这样其他人就不用花时间搞清楚到底发生了什么。
[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;
}
}