Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 244
Sunday Ironfoot Avatar asked Mar 23 '10 14:03

Sunday Ironfoot


2 Answers

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. :)

like image 72
Keith K Avatar answered Sep 28 '22 02:09

Keith K


I don't believe it's possible to modify the registered HttpHandlers once the AppDomain is running because the available handlers is read directly from the web.config file then cached in a private data structure.

If you knew upfront which extensions you wanted to allow, you could do is map these extensions to a single HttpHandlerFactory and then return a handler of your choice (by using dynamic assembly loading and reflection). For example:

<add path="*.ch1,*.ch2,*.ch3" verb="*" 
    type="MyHandlers.MyHandlerFactory, MyHandlers" />

Modifying the web.config at runtime would cause the AppDomain to restart.

like image 32
Kev Avatar answered Sep 28 '22 02:09

Kev