Last post Jun 16, 2006 12:30 PM by DavidDu
Jun 15, 2006 12:21 PM|DavidDu|LINK
I was trying to figure out what is the advantage to use HttpHandlerfactory? HttpHandler seem already good enough for all the situation. Can somebody point out a situation as we have to use httphandlerfactory, or httphandlerfactory will bring in more benefit.
Jun 15, 2006 09:04 PM|SomeNewKid|LINK
You would use an IHttpHandler when you know precisely the handler that needs to be used. For example, you may have an XmlHttpHandler that is assigned to requests for .xml documents. In your web.config file, you would point .xml
documents directly to the XmlHttpHandler.
You would use an IHttpHandlerFactory when you do not know precisely the handler that needs to be used. For example, you may have a handful of JPEG handlers that may be needed to respond to a request for a .jpg document. If the
user is anonymous, you need to use the StampedJpegHttpHandler (it stamps a big copyright notice over the JPEG). If the user is logged in, you need to use the JpegHttpHandler (it returns the JPEG without copyright notices). If the request is for a file within
the /protected folder, you need to use the ProtectedJpegHttpHandler (it embeds copyright information into the metadata of the returned JPEG). Of course, I am just making these examples up.
But the point is, when the request is for a .jpg file, you do not know precisely the handler to be used. It may be a StampedJpegHttpHandler, a JpegHttpHandler, or a ProtectedJpegHttpHandler. You can't perform this sort of logic in the web.config file.
You need to create a JpegHttpHandlerFactory, and the job of the factory is to return one of these three HttpHandlers.
Actually, to give you a real example, my application uses a JpegHandlerFactory that returns one of three different HttpHandlers. Here is the relevant code:
public class JpegHandlerFactory : IHttpHandlerFactory
public IHttpHandler GetHandler
(HttpContext context, String requestType, String url, String pathTranslated)
IHttpHandler handler = null;
// Is this a leeching request?
// Request is valid if the referrer is null,
// or if the referrer is the same as the host.
Uri referrer = context.Request.UrlReferrer;
Boolean validReferrer = (
referrer == null ||
referrer.Host.Length == 0 ||
referrer.Host.CompareTo(context.Request.Url.Host.ToString()) == 0
if (validReferrer == false)
handler = new ForbiddenHandler();
// is this a static JPEG file?
if (handler == null)
String staticFile = context.Request.PhysicalPath;
handler = new JpegHandler();
if (handler == null)
handler = new NotFoundHandler();
public void ReleaseHandler(IHttpHandler handler)
I hope this helps you.
Jun 16, 2006 12:30 PM|DavidDu|LINK