Enabling Session State In IHttpHandlers

Sometimes it is handy to have the HttpSession available from your custom IHttpHandlers. By default the session state is unavailable from IHttpHandlers, and attempting to access it will result in a NullReferenceException. To make session state available simply implement the IRequireSessionState interface.

using System.Web;
using System.Web.SessionState;

public class SomeHandler : IHttpHandler, IRequiresSessionState {

     public void ProcessRequest(HttpContext context){
          //do processing that requires session state.
	  //use the context.Session to acquire the session state.
     }

     public bool IsReusable {
          get { return false; }
     }
}

The IRequiresSessionState interface is simply a marker interface, thus it has no members to implement. Once implemented your IHttpHandler can acquire the session state using the Session property of the HttpContext parameter on the ProcessRequest method.