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

Bha*_*kar 76 asp.net

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

Nic*_*rey 109

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

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

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

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

该属性HttpApplication的实现Session抛出HttpException了消息Session state is not available in this context.而不是返回null引用.

其中一些HttpHandler不实现会话的示例是通常静态资源的默认处理程序,例如图像和CSS文件.任何参考HttpApplicationSession在这种情况下属性(如在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;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 没问题.我刚刚有一个相当讨厌的WTF?需要一些时间来解决的时刻.我想我会记录下来,所以其他人不必花时间搞清楚发生了什么. (11认同)
  • 感谢您付出努力来填写更好的答案. (8认同)

Phi*_*ert 8

没有区别.

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