Search code examples
c#httphandlerremap

Is HttpContext.RemapHandler supposed to change which handler processes request?


The MSDN documentation says:

HttpContext.RemapHandler Method - Enables you to specify a handler for the request.

I am trying to move the processing of the request from one handler to another depending on a condition in the first handler. The HttpContext.RemapHandler method seems to initialise an instance of the second handler but not call the HttpHandler.ProcessRequest method; the response is empty.

Does the HttpContext.RemapHandler method do what I think it should - transfer processing to a new HttpHandler and calling the HttpHandler.ProcessRequest method? Or should I be using another approach such as another method or an HttpModule?

EDIT: Turns out I should be using a HTTPHandlerFactory. I have the solution working nicely now.

So what exactly is HttpContext.RemapHandler for?


Solution

  • You can use HttpContext.RemapHandler as you specified, however if another HttpHandler calls RemapHandler (e.g. ASP.NET MVC which registers MvcHandler in PostResolveRequestCache) your IHttpModule will never fire. This is maybe why IHttpHandler.Process was never called.

    If this is your issue, you can simply define a route to ignore in MvcApplication.RegisterRoutes like this:

    routes.IgnoreRoute("your_path/{*pathInfo}");
    

    Also, remember that with Visual Studio Web Development Server and IIS6, RemapHandler will not work.

    Here is an example of how to select the right way to remap the handler based on whether or not Integrated Pipeline is activated AND still be able to access the session:

    public void Init(HttpApplication application)
    {
      if (HttpRuntime.UsingIntegratedPipeline)
        // For IIS 7 and IIS 8
        application.PostAuthorizeRequest += Application_PostAuthorizeRequest;
      else
        // For IIS 6
        application.PostMapRequestHandler += Application_PostMapRequestHandler;
    }
    
    private void Application_PostAuthorizeRequest(object sender, EventArgs e)
    {
        ((HttpApplication)sender).Context.RemapHandler(_myHandler);
    }
    
    private void Application_PostMapRequestHandler(object sender, EventArgs e)
    {
        ((HttpApplication)sender).Context.Handler = _myHandler;
    }
    

    The difference between using a HttpHandlerFactory and HttpModule in this case is that the latter allows you to decide when to use which IHttpHandler regardless of ASP.NET IHttpHandler mappings. More on MSDN: HTTP Handlers and HTTP Modules Overview.