Session和HttpContext.Current.Session对象之间有什么区别?
Answers:
这里有点晚,但这是我刚刚发现的东西。
@Phillipe Leybaert和@CSharpAtl都不正确。HttpApplication的Session财产表现出与财产不同的行为HttpContext.Current.Session。如果一个HttpSessionState实例可用,它们都将返回对同一实例的引用。当当前请求没有可用实例时,它们的操作有所不同。HttpSessionState
并非所有人都HttpHandler提供会话状态。为此,HttpHandler 必须实现[一个或两个?]标记接口IRequiresSessionState或IReadOnlySessionState。
HttpContext.Current.Sessionnull如果没有会话可用,则仅返回。
在HttpApplication所述的的实现Session属性会引发HttpException与所述消息Session state is not available in this context.,而不是返回一个null参考。
HttpHandler无法实现会话的一些示例是通常静态资源(例如图像和CSS文件)的默认处理程序。在这种情况下(例如在事件处理程序中)HttpApplication对的Session属性的任何引用global.asax都会导致HttpException被抛出。
不用说,意外HttpException提供了WTF ?!如果您不期望的话。
因此Session,HttpApplication该类的属性得以实现(来自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;
}
}
在内部,Page.Session点,这是HttpContext.Current.Session只,但仍有从那里它被称为取决于两点不同。
只能从从System.Web.UI.Page继承的类访问Page.Session,并且从WebMethod访问时它将抛出HttpException。
只要您在Web应用程序上下文中运行,就可以从任何地方访问HttpContext.Current.Session。
可以访问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。