ASP.NET - Dynamically register an HttpHandler in code (not in web.config)

Sunday Ironfoot picture Sunday Ironfoot · Mar 23, 2010 · Viewed 12.7k times · Source

Possible Duplicate:
Any way to add HttpHandler programatically in .NET?

Is there a way I can dynamically register an IHttpHandler in C# code, instead of having to manually add it to the system.web/httpHandlers section in the web.config.

This may sound crazy, but I have good reason for doing this. I'm building a WidgetLibrary that a website owner can use just by dropping a .dll file into their bin directory, and want to support this with minimal configuration to the web.config.

Answer

Keith K picture Keith K · Sep 6, 2011

You can't modify the handlers but you can add a route to your hander programatically following these steps:

  1. If its a WebForms app then ensure your webapp has the UrlRouting configuration in the web.config (yip breaks part of your initial requirement to have minimal changes to web.config) as explained by MS here: Use Routing with Web Forms
  2. Implement the IRouteHandler interface on your handler and return the hander as the result in its methods (see first example below)
  3. Register your route (see second example below)

Implement IRouteHandler

public class myHandler : IHttpHandler, IRouteHandler
{
    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        // your processing here
    }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return this;
    }
}

Register Route:

//from global.asax.cs
protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.Add(new Route
    (
        "myHander.axd",
        new myHandler()
    ));
}

There you have it. A hander registered though code. :)