Session 和 HttpContext.Current.Session 的区别 [英] Difference between Session and HttpContext.Current.Session
问题描述
Session 和 HttpContext.Current.Session 对象有什么区别?
What is the difference between Session and HttpContext.Current.Session object?
推荐答案
这里有点晚了,但这是我刚刚发现的东西.
A little late here, but here's something I just discovered.
@Phillipe Leybaert 和@CSharpAtl 都是错误的.HttpApplication
的 Session
属性表现出与 HttpContext.Current.Session
属性不同的行为.它们都将返回对同一个 HttpSessionState
实例的引用 如果 一个可用.当没有可用于当前请求的 HttpSessionState
实例时,它们的不同之处在于它们所做的.
@Phillipe Leybaert and @CSharpAtl are both incorrect. HttpApplication
's Session
property exhibits different behaviour than does that of the property HttpContext.Current.Session
. They will both return a reference to the same HttpSessionState
instance if one is available. They differ in what they do when there is no instance of HttpSessionState
available for the current request.
并非所有 HttpHandler
都提供会话状态.为此,HttpHandler
必须实现[一个或两个?]标记接口IRequiresSessionState
或IReadOnlySessionState
.
Not all HttpHandler
s provide session state. To do so, the HttpHandler
must implement [one or both?] the marker interfaces IRequiresSessionState
or IReadOnlySessionState
.
HttpContext.Current.Session
如果没有可用的会话,则只返回 null
.
HttpContext.Current.Session
simply returns null
if there is no session available.
HttpApplication
对 Session
属性的实现抛出一个 HttpException
消息 Session state is not available in this context.
而不是返回 null
引用.
The HttpApplication
's implementation of the Session
property throws an HttpException
with the message Session state is not available in this context.
rather than returning a null
reference.
一些没有实现会话的 HttpHandler
示例是通常静态资源(例如图像和 CSS 文件)的默认处理程序.在这种情况下(如在 global.asax
事件处理程序中)对 HttpApplication
的 Session
属性的任何引用都将导致 HttpException
被抛出.
Some examples of HttpHandler
that do not implement session are the default handlers for normally static resources, such as image and CSS files. Any reference to the HttpApplication
's Session
property in such cases (as in global.asax
event handlers) will result an HttpException
being thrown.
不用说,意外的 HttpException
提供了一个 WTF?!如果你不期待它,那一刻.
Needless to say, the unexpected HttpException
provides a WTF?! moment if you're not expecting it.
HttpApplication
类的 Session
属性是这样实现的(来自反射器):
The Session
property of the HttpApplication
class is implemented thus (from 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;
}
}
这篇关于Session 和 HttpContext.Current.Session 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!