I've googled. I've forumed. I've dissassembled.
I was unable to find any API for determining, at runtime, from a custom control, if a custom IHttpHandler in the same assembly has been registered correctly for the application that my custom control is running in. This makes it rather awkward to do IHttpHandlers in 3rd party components, as there's no nice way to alert the developer that things aren't set up quite right. A 404 error isn't very useful if the developer didn't know he was supposed to register a handler.
So at this point, I gave up trying to do things a nice way, and wrote a horribly hackish helper function to determine if a handler is installed. I decided to make a full webrequest to my own application looking for the handler. A 404 means it's not installed correctly. Of course, I cache the result so I'm not doing this too often. here you go:
private void EnsureHandler(String handlerName) {
String key = "IHttpHandler Installed " + handlerName;
if ( HttpContext.Current.Cache[key] == null ) {
Uri url = HttpContext.Current.Request.Url;
String urlForHandler = "http://" + url.Host + ":" + url.Port.ToString() + this.ResolveUrl("~/" + handlerName);
System.Net.WebRequest request = System.Net.WebRequest.Create(urlForHandler);
try {
System.Net.WebResponse myResponse = request.GetResponse();
HttpContext.Current.Cache[key] = true;
} catch( System.Net.WebException ex ) {
HttpContext.Current.Cache[key] = false;
}
}
Boolean isInstalled = (Boolean)HttpContext.Current.Cache[key];
if ( !isInstalled ) {
throw new ApplicationException("The '" + handlerName + "' handler must be installed in web.config.");
}
}
This code assumes that the handler is a specific, fully-named handler, like MyReallyCoolHandler.axd.
It also assumes that the handler won't throw an exception if the handler is called with an empty query string. You may want to adjust the querystring and your handler so that can do something simple that doesnt' throw an exception when testing for the handler's existance like this.
Oh, and if you know of a good way to do this... PLEASE let me know.
UPDATE
Scott wanted to know why I don't just check the web.config. You can't do that, because the httphandler might be registered in any .config up the chain, including machine.config. It would give out false positives.