Call the default asp.net HttpHandler from a custom handler

后端 未结 3 1069

I\'m adding ASP.NET routing to an older webforms app. I\'m using a custom HttpHandler to process everything. In some situations I would like to map a particular pat

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-03 11:31

    Persistence pays off! This actually works, and since this information seems to be available pretty much nowhere I thought I'd answer my own question. Thanks to Robert for this post on instantiating things with internal constructors, this is the key.

    http://www.rvenables.com/2009/08/instantiating-classes-with-internal-constructors/

    public void ProcessRequest(HttpContext context) {
        // the internal constructor doesn't do anything but prevent you from instantiating
        // the factory, so we can skip it.
        PageHandlerFactory factory =
            (PageHandlerFactory)System.Runtime.Serialization.FormatterServices
            .GetUninitializedObject(typeof(System.Web.UI.PageHandlerFactory));
    
         string newTarget  = "default.aspx"; 
         string newQueryString = // whatever you want
         string oldQueryString = context.Request.QueryString.ToString();
         string queryString = newQueryString + oldQueryString!="" ? 
             "&" + newQueryString :
             "";
    
         // the 3rd parameter must be just the file name.
         // the 4th parameter should be the physical path to the file, though it also
         //   works fine if you pass an empty string - perhaps that's only to override
         //   the usual presentation based on the path?
    
         var handler = factory.GetHandler(context, "GET",newTarget,
             context.Request.MapPath(context,newTarget));
    
         // Update the context object as it should appear to your page/app, and
         // assign your new handler.
    
         context.RewritePath(newTarget  , "", queryString);
         context.Handler = handler;
    
         // .. and done
    
         handler.ProcessRequest(context);
    }
    

    ... and like some small miracle, an aspx page processes & renders completely in-process without the need to redirect.

    I expect this will only work in IIS7.

提交回复
热议问题