Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

asp.net - Difference between Session and HttpContext.Current.Session

What is the difference between Session and HttpContext.Current.Session object?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A little late here, but here's something I just discovered.

@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.

Not all HttpHandlers provide session state. To do so, the HttpHandler must implement [one or both?] the marker interfaces IRequiresSessionState or IReadOnlySessionState.

HttpContext.Current.Session simply returns null if there is no session available.

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.

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.

Needless to say, the unexpected HttpException provides a WTF?! moment if you're not expecting it.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...