【问题标题】:Difference between Session and HttpContext.Current.SessionSession 和 HttpContext.Current.Session 的区别
【发布时间】:2009-06-02 17:14:27
【问题描述】:

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

【问题讨论】:

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

标签: asp.net


【解决方案1】:

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

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

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

如果没有可用的会话,HttpContext.Current.Session 只会返回 null

HttpApplicationSession 属性的实现会抛出带有消息 Session state is not available in this context.HttpException,而不是返回 null 引用。

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

不用说,意想不到的HttpException提供了一个WTF?!如果你不期待它的时刻。

HttpApplication 类的Session 属性是这样实现的(来自 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;
  }
}

【讨论】:

  • 感谢您努力填写更好的答案。
  • 没问题。我刚刚有一个相当烦人的WTF?花了一些时间来整理的那一刻。我想我会把它记录下来,这样其他人就不必花时间弄清楚发生了什么。
【解决方案2】:

没有区别。

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

【讨论】:

    【解决方案3】:

    什么都没有。 Session 只是指向HttpContext.Current.Session

    【讨论】:

      【解决方案4】:

      在内部,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会抛出null引用异常,但是Page.Session还是会附加页面对象,所以页面方法GetData可以访问Page.Session。

      【讨论】:

        猜你喜欢
        • 2011-12-18
        • 2015-12-05
        • 2017-10-14
        • 2021-10-11
        • 2014-06-27
        • 2019-08-25
        • 2019-06-04
        • 2013-11-21
        • 1970-01-01
        相关资源
        最近更新 更多