tags:

views:

717

answers:

2

In ASP.NET, when building a web server control in a class library that includes an HttpHandler is there a way to automatically register the handler without having to manually edit the web application's web.config file?

I have a class library that contains a CompositeControl. In the composite control I have an Image control with a ImageUrl property set to an HttpHandler. In order for the HttpHandler to work from an application that uses the class library I have to make an entry in the web.config file:

<add verb="*" path="Icon.ashx" type="ClassLibrary.MyHandler" />

I've read this blog post which outlines how to trick the designer into doing this for you, but I'd like something that doesn't require the user of my class library to enter the designer in Visual Studio for this to work.

+3  A: 

I don't think there's any way to register a handler at runtime. A variation of the code you already have will modify other parts of web.config at runtime, but quietly fails if you try to modify <httpHandlers>. You could parse and edit web.config as if it were any other XML file, but you can't necessarily assume that the application has write access to web.config at runtime.

However, you could achieve the same effect as a HttpHandler by handling the application's BeginRequest event. Add an event handler the first time that your control loads, and in that handler you can check whether Request.Url is one that you should take care of, and if so call your ProcessRequest code. Finally, call HttpApplication.CompleteRequest() to skip the normal request handling. You'll add a little overhead to every request, so it's up to you whether that's worthwhile to avoid a manual web.config edit.

A partial solution would be to use that IsHttpHandlerRegistered() method at runtime so that you can give a helpful exception if the handler isn't registered. This seems to be how ASP.NET itself deals with features that require a HttpHandler. Reading the config should be fine at runtime, though getting the Configuration object will be slightly different:

Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
stevemegson
very helpful! i'll leave this open for a while to see if anyone else has other ideas... otherwise we might have to make this the "accepted answer"
Shawn Miller
+1  A: 

http://www.tkachenko.com/blog/archives/000686.html