IHttpHandlerFactory and URL Mapping


There are many ways to create a complete URL Mapping solution. But most of the serious URL Mapping code, utilizes something a little more advanced than the urlMapping node in Web.Config.

The next level up from my previous post, needs to take you into the world of HTTP Handlers. I did not have all the time in the world on this post, so I have decided to put some simple elements of the solution, rather than a complete tutorial. I trust using any keywords from here, you will find lots of other resources.

This post will just simply look at a small example of the IHttpHandlerFactory interface and the Web.Config settings.

What you need to do:

1. Implement the IHttpHandlerFactory 
2. Configure Web.Config with your handler


The Interface

public class DefaultPageHandler : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
}

public void ReleaseHandler(IHttpHandler handler)
{
}



}


The Web.Config

<httpHandlers> 

<remove verb="POST,GET" path="*.ext"/>
<add verb="POST,GET" path="*.ext" type="DefaultPageHandler"/>

</httpHandlers>

Web.Config Dynamic update?

A good solution can map these up itself. Here is how you dynamically add a handler section to the Web.Config. Dynamically adding this is useful for mapping extensions, and perhaps even paths dynamically. Below is sample code:

#region write to web.config
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
 
            HttpHandlersSection section =
              (HttpHandlersSection)config.GetSection("system.web/httpHandlers");
 
            HttpHandlerAction actionAdd = 
               new HttpHandlerAction("/*.ext","DefaultPageHandler","POST,GET");
            
            section.Handlers.Add(actionAdd);
            
            config.Save();
 
#endregion