문제

httpmodule 내에서 사용자의 세션 변수를 업데이트 할 수는 있지만 볼 수있는 것은 불가능합니다.

업데이트: 내 코드는 현재 내부에서 실행 중입니다 OnBeginRequest () 이벤트 핸들러.

업데이트: 지금까지받은 조언에 따라 나는 이것을 Init () 내 httpmodule의 일상 :

AddHandler context.PreRequestHandlerExecute, AddressOf OnPreRequestHandlerExecute

그러나 내 OnPreRequestHandlerExecute 일상적인 세션 상태는 여전히 사용할 수 없습니다!

감사합니다. 내가 뭔가를 놓치면 사과드립니다!

도움이 되었습니까?

해결책

이것을 찾았습니다 ASP.NET 포럼:

using System;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Diagnostics;

// This code demonstrates how to make session state available in HttpModule,
// regradless of requested resource.
// author: Tomasz Jastrzebski

public class MyHttpModule : IHttpModule
{
   public void Init(HttpApplication application)
   {
      application.PostAcquireRequestState += new EventHandler(Application_PostAcquireRequestState);
      application.PostMapRequestHandler += new EventHandler(Application_PostMapRequestHandler);
   }

   void Application_PostMapRequestHandler(object source, EventArgs e)
   {
      HttpApplication app = (HttpApplication)source;

      if (app.Context.Handler is IReadOnlySessionState || app.Context.Handler is IRequiresSessionState) {
         // no need to replace the current handler
         return;
      }

      // swap the current handler
      app.Context.Handler = new MyHttpHandler(app.Context.Handler);
   }

   void Application_PostAcquireRequestState(object source, EventArgs e)
   {
      HttpApplication app = (HttpApplication)source;

      MyHttpHandler resourceHttpHandler = HttpContext.Current.Handler as MyHttpHandler;

      if (resourceHttpHandler != null) {
         // set the original handler back
         HttpContext.Current.Handler = resourceHttpHandler.OriginalHandler;
      }

      // -> at this point session state should be available

      Debug.Assert(app.Session != null, "it did not work :(");
   }

   public void Dispose()
   {

   }

   // a temp handler used to force the SessionStateModule to load session state
   public class MyHttpHandler : IHttpHandler, IRequiresSessionState
   {
      internal readonly IHttpHandler OriginalHandler;

      public MyHttpHandler(IHttpHandler originalHandler)
      {
         OriginalHandler = originalHandler;
      }

      public void ProcessRequest(HttpContext context)
      {
         // do not worry, ProcessRequest() will not be called, but let's be safe
         throw new InvalidOperationException("MyHttpHandler cannot process requests.");
      }

      public bool IsReusable
      {
         // IsReusable must be set to false since class has a member!
         get { return false; }
      }
   }
}

다른 팁

httpcontext.current.session HTTP 모듈이 처리하지 않는다고 가정하면 작동해야합니다. 파이프 라인 이벤트 세션 상태가 초기화되기 전에 발생합니다 ...

주석에서 설명 후 편집 : 처리 할 때 시작 이벤트, 세션 객체는 아직 ASP.NET 런타임에 의해 초기화되지 않았기 때문에 실제로 NULL/NOTED입니다. 이 문제를 해결하려면 취급 코드를 후에 발생한 이벤트로 옮깁니다. Acquirerequeststate -- 좋아요 perrequesthandlerexecute 이 단계에서는 모든 저급 작업이 거의 이루어 지지만 여전히 정상적인 처리를 선점합니다.

액세스 HttpContext.Current.Session 안에 IHttpModule 에서 수행 할 수 있습니다 PreRequestHandlerExecute 매니저.

perrequesthandlerexecute: "ASP.NET이 이벤트 핸들러를 실행하기 시작하기 직전에 발생합니다 (예 : 페이지 또는 XML 웹 서비스)." 이는 'ASPX'페이지가 제공되기 전에이 이벤트가 실행되기를 의미합니다. '세션 상태'를 사용할 수 있으므로 자신을 때릴 수 있습니다.

예시:

public class SessionModule : IHttpModule 
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += BeginTransaction;
            context.EndRequest += CommitAndCloseSession;
            context.PreRequestHandlerExecute += PreRequestHandlerExecute;
        }



        public void Dispose() { }

        public void PreRequestHandlerExecute(object sender, EventArgs e)
        {
            var context = ((HttpApplication)sender).Context;
            context.Session["some_sesion"] = new SomeObject();
        }
...
}

페이지 나 핸들러를 통해 ASP.NET 요청에 신청하려는 관리 응용 프로그램에 일반적이고 기본적인 HTTPModule을 작성하는 경우 세션 생성 후 수명주기에서 이벤트를 사용해야합니다. start_request 대신 perrequesthandlerexecute는 보통 내가가는 곳입니다. MDB는 자신의 편집에 바로 그것을 가지고 있습니다.

더 긴 코드 스 니펫은 원래 질문에 응답하는 것으로 나열되었지만 초기 질문보다 복잡하고 광범위합니다. IREQUIRESSESSIONSTATE 인터페이스를 구현할 수있는 ASP.NET 핸들러가없는 내용에서 컨텐츠가 제공되는 경우 사례를 처리하여 세션 메커니즘을 트리거하여 사용할 수 있도록합니다. (디스크의 정적 GIF 파일과 유사). 기본적으로 더미 핸들러를 설정하여 해당 인터페이스를 구현하여 세션을 사용할 수 있도록합니다.

코드의 세션 만 원한다면 모듈에서 처리 할 올바른 이벤트를 선택하십시오.

시도해보십시오 : 클래스 myhttpmodule에서 : 다음 :

private HttpApplication contextapp;

그 다음에:

public void Init(HttpApplication application)
{
     //Must be after AcquireRequestState - the session exist after RequestState
     application.PostAcquireRequestState += new EventHandler(MyNewEvent);
     this.contextapp=application;
}  

따라서 같은 클래스의 다른 방법 (이벤트)에서 :

public void MyNewEvent(object sender, EventArgs e)
{
    //A example...
    if(contextoapp.Context.Session != null)
    {
       this.contextapp.Context.Session.Timeout=30;
       System.Diagnostics.Debug.WriteLine("Timeout changed");
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top