Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 会话和HttpContext.Current.Session之间的差异_Asp.net - Fatal编程技术网

Asp.net 会话和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

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

没有区别


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;
  }
}