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


77

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


3
值得澄清的是,当您说“会话”时,是指System.Web.UI.Page.Session。Session对象在ASP.NET页的上下文中可用。
Llyle

Answers:


111

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

@Phillipe Leybaert和@CSharpAtl都不正确。HttpApplicationSession财产表现出与财产不同的行为HttpContext.Current.Session如果一个HttpSessionState实例可用,它们都将返回对同一实例的引用。当当前请求没有可用实例时,它们的操作有所不同。HttpSessionState

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

HttpContext.Current.Sessionnull如果没有会话可用,则仅返回。

HttpApplication所述的的实现Session属性会引发HttpException与所述消息Session state is not available in this context.,而不是返回一个null参考。

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

不用说,意外HttpException提供了WTF ?!如果您不期望的话。

因此SessionHttpApplication该类的属性得以实现(来自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;
  }
}

9
感谢您为填写更好的答案而付出的努力。
nicodemus13 2011年

12
没问题。我刚刚有一个相当烦人的WTF?花费一些时间进行整理的那一刻。我以为自己要记录下来,这样一来其他人就不必花时间弄清楚发生了什么。
尼古拉斯·凯里



1

在内部,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。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.