Can I access session state from an HTTPModule? Can I access session state from an HTTPModule? asp.net asp.net

Can I access session state from an HTTPModule?


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,// regardless of requested resource.// author: Tomasz Jastrzebskipublic 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 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.


Accessing the HttpContext.Current.Session in a IHttpModule can be done in the PreRequestHandlerExecute handler.

PreRequestHandlerExecute: "Occurs just before ASP.NET starts executing an event handler (for example, a page or an XML Web service)." This means that before an 'aspx' page is served this event gets executed. The 'session state' is available so you can knock yourself out.

Example:

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();        }...}