views:

6857

answers:

3

Hi,

I could really do with updating a user's session variables from within my HTTPModule, but from what I can see, it isn't possible.

UPDATE: My code is currently running inside the OnBeginRequest () event handler.

UPDATE: Following advice received so far, I tried adding this to the Init () routine in my HTTPModule:

AddHandler context.PreRequestHandlerExecute, AddressOf OnPreRequestHandlerExecute

But in my OnPreRequestHandlerExecute routine, the session state is still unavailable!

Thanks, and apologies if I'm missing something!

+10  A: 

HttpContext.Current.Session should Just Work, assuming your HTTP Module isn't handling any pipeline events that occur prior to the session state being initialized...

EDIT, after clarification in comments: when handling the BeginRequest event, the Session object will indeed still be null/Nothing, as it hasn't been initialized by the ASP.NET runtime yet. To work around this, move your handling code to an event that occurs after PostAcquireRequestState -- I like PreRequestHandlerExecute for that myself, as all low-level work is pretty much done at this stage, but you still pre-empt any normal processing.

mdb
Unfortunately that's not available in the HTTPModule - "Object reference not set to an instance of an object."
Chris Roberts
I'm processing 'OnBeginRequest'?
Chris Roberts
Thanks for the update. If I handle it in an Application level event, why don't I just do all my processing at application level instead of using an HTTPModule?
Chris Roberts
PostAcquireRequeststate isn't an 'application level event': if the HTTP request is handled by a web service handler, for example, you'll still see it in your HTTP module, but not in Global.asax...
mdb
+16  A: 

Found this over on the ASP.NET forums:

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; }
      }
   }
}
Jim Harte
Thanks - this code did the trick!
Chris Roberts
sexy code ..::..
Andrija
MS should to fix this!... if i mark a Module as implementing the IRequiresSessionState, i shouldn't have to jump thru a hoop to get it... ( sexy code indeed )
BigBlondeViking
Nice code. I thought I would need this, but it turns out not. This code ends up loading the session for every image and other non-page resource that goes through the server. In my case, I simply check if session is null in the PostAcquireRequestState event and return if it is.
Abtin Forouzandeh
This code is useful if the resource requested doesn't handle session state. For standard .aspx pages simply add your code accessing the session on the PostAcquireRequestState event handler.Session state won't be available on any BeginRequest event handler because the session state has not been acquired yet.
JCallico
Fantastic. Thx amigo, this code really did the trick to use HttpContext.Current.User within an HttpModule
Sem Dendoncker
+5  A: 

If you're writing a normal, basic HttpModule in a managed application that you want to apply to asp.net requests through pages or handlers, you just have to make sure you're using an event in the lifecycle after session creation. PreRequestHandlerExecute instead of Begin_Request is usually where I go. mdb has it right in his edit.

The longer code snippet originally listed as answering the question works, but is complicated and broader than the initial question. It will handle the case when the content is coming from something that doesn't have an ASP.net handler available where you can implement the IRequiresSessionState interface, thus triggering the session mechanism to make it available. (Like a static gif file on disk). It's basically setting a dummy handler that then just implements that interface to make the session available.

If you just want the session for your code, just pick the right event to handle in your module.

Rob