IT박스

Session과 HttpContext.Current.Session의 차이점

itboxs 2020. 10. 17. 10:05
반응형

Session과 HttpContext.Current.Session의 차이점


Session과 HttpContext.Current.Session 객체의 차이점은 무엇입니까?


여기서 조금 늦었지만 방금 발견 한 것이 있습니다.

@Phillipe Leybaert 및 @CSharpAtl이 모두 올바르지 않습니다. HttpApplicationSession재산은 재산과는 다른 행동을 보인다 HttpContext.Current.Session. 둘 다 사용 가능한 경우 동일한 HttpSessionState인스턴스에 대한 참조를 반환 합니다. 현재 요청 사용할 수있는 인스턴스가 없을 때 수행하는 작업이 다릅니다 .HttpSessionState

모든에서 HttpHandler세션 상태를 제공하는 것은 아닙니다 . 이렇게하려면이 HttpHandler 있어야합니다 [하나 또는 모두를?] 구현하는 마커 인터페이스 IRequiresSessionStateIReadOnlySessionState.

HttpContext.Current.Sessionnull사용 가능한 세션이 없으면 간단히 반환 됩니다.

속성 HttpApplication구현은 참조를 반환하는 대신 메시지와 함께를 Sessionthrow합니다 .HttpExceptionSession state is not available in this context.null

HttpHandler세션을 구현하지 않는 몇 가지 예는 이미지 및 CSS 파일과 같은 일반적으로 정적 리소스에 대한 기본 처리기입니다. 이러한 경우 ( 이벤트 처리기 에서와 같이) HttpApplicationSession속성에 대한 모든 참조 는 throw됩니다.global.asaxHttpException

말할 것도없이 예상치 못한 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;
  }
}

다른 점이 없다.

Page.Session의 getter는 컨텍스트 세션을 반환합니다.


아무것도. Session단지 HttpContext.Current.Session.


내부적으로 Page.Session은 It 's HttpContext.Current.Session만을 가리 키지 만 호출 된 위치에 따라 여전히 두 가지 차이점이 있습니다.

Page.Session can be accessed only from classes inherited from System.Web.UI.Page and it will throw HttpException when accessed from WebMethod.
Where as HttpContext.Current.Session can be accessed from anywhere as long as you're running in the context of a web application.


Other important difference where you can access Page.Session but cannot access HttpContext.Current.Session :

If there is a method named GetData in your page(inherited from System.Web.UI.Page) which is executed concurrently in different threads from some other page method, GetData method can access the Page.Seession, but you cannot access HttpContext.Current.Session.

It's because GetData has been called from different thread so HttpContext.Current is null and HttpContext.Current.Session will throw null reference exception, but Page.Session will still be attached with page object so page method GetData can access the Page.Session.

참고URL : https://stackoverflow.com/questions/940742/difference-between-session-and-httpcontext-current-session

반응형