Using IHttpHandlerFactory

You can use the IHttpHandlerFactory interface to dynamically handle page requests and send them to instances of IHttpHandler.

In this example I will show you how to implement both the IHttpHandlerFactory and IHttpHandler to handle requests for pages that do not exist and return page content describing the Request variables.

Implement the IHttpHandlerFactory:


namespace HttpHandlerFactoryTestApp
{
    public class HttpHandlerFactoryImpl : IHttpHandlerFactory
    {
        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            return new HttpHandlerImpl();
        }

        public void ReleaseHandler(IHttpHandler handler) {}
    }
}

You will notice that the GetHandler method returns an object of type IHttpHandler. Next we implement our custom IHttpHandler for our IHttpHandlerFactory to return.


namespace HttpHandlerFactoryTestApp
{
    public class HttpHandlerImpl : IHttpHandler
    {
        public void ProcessRequest(HttpContext ctx)
        {
            ctx.Response.Write(string.Format("{1}", 1, ctx.Request.ServerVariables["URL"]));

            foreach (string key in ctx.Request.ServerVariables.AllKeys)
            {
                ctx.Response.Write(string.Format("{0}: {1} <{2}/>", key, ctx.Request.ServerVariables[key], "br"));
            }
        }

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

In the ProcessRequest method I write all the server variables to the response. (I had to tweak the embedded html code so this article would format correctly).

To make this work you need to register the IHttpHandlerFactory in the HttpHandlers section of your web.config

For IIS 6



    
    ...
        
    

For IIS 7



    
        ...
        
        


Finally I added a static Html file with a set of links to pages that do not exist.


    

Test Pages

  1. Example
  2. Example 2
  3. Factory Design Pattern
  4. Folder Example
  5. Sub Folder Example

Don’t forget to set the html page as your start up page.

You should now be able to start up the example and click on any of the links and see content.



Comments

No comments yet.

Add Yours

  • Author Avatar

    YOU


Comment Arrow




About Author

Robert

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning hands down.