Session和HttpContext.Current.Session对象有什么区别?
Nic*_*rey 109
这里有点晚了,但这是我刚发现的东西.
@Phillipe Leybaert和@CSharpAtl都不正确.HttpApplication的Session财产表现出与财产不同的行为HttpContext.Current.Session.如果有可用,它们都将返回对同一HttpSessionState实例的引用.当没有可用于当前请求的实例时,它们的作用不同.HttpSessionState
并非所有HttpHandlers都提供会话状态.为此,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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64058 次 |
| 最近记录: |