My first blog post from Word 2007 – let’s see how this goes.
Introduction
There are many features in ASP.NET that are unfortunately underused. Sometimes a feature gets looked over because it’s too complicated. Other times, like in the case of HttpHandlers, it’s because they are poorly understood. For the longest time I understood the concept and implementation of HttpHandlers, but I just couldn’t figure out under what circumstances I’d use them.
Googling HttpHandlers it’s obvious to me that bad tech writers are squarely to blame. A shameful amount of examples are nothing more than “hello world.” The problem with such a limited example is that it leaves the reader thinking “so? I can do that with an aspx page!” Without understanding what problem space HttpHandlers are meant for, it’s impossible to get developers to use them.
As an ASP.NET developer, HttpHandlers are important because they are the earliest possible point where you have access to requests. When a request is made to IIS for an ASP.NET resource (.aspx, .config, .asmx), the ASP.NET worker process internally creates an instance of the right HttpHandler for the request in question and effectively hands off the task of responding to the request. How does ASP.NET know which is the right HttpHandler for a given request? Simple, via configuration files, paths are mapped to http handlers. For example, if you open your machine.config file you’ll see a list of default mapping. For example:
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory" />
<add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="*.asmx" type="System.Web.Services.Protocols.WebServiceHandlerFactory" />
So every time any .aspx page is requested, the PageHandlerFactory is left to fulfill the request. HttpHandlers can also be added or changed for specific sites in the web.config. Handlers aren’t just mapped to extensions, your own handler can be mapped to “HandlePingback.aspx”, in which case it, not the PageHandlerFactory, will be called upon.
An HttpHandler is actually any class that implements the System.Web.IHttpHandler interface. To be of any use it needs to be mapped to a path. (I lie, PageHandlerFactory doesn’t implement IHttpHandler. Instead, it implements IHttpHandlerFactory. IHttpHandlerFactory defines a method named GetHandler which returns an IHttpHandler. We won’t cover IHttpHandlerFactories here, but it’s basically a layer between the internal ASP.NET process and the handoff to the HttpHandler. Either way, in the end you end up with a class that implements IHttpHandler). The IHttpHandler interfaces defines the very important and aptly named ProcessRequest. Basically, this is ASP.NET saying “hey you! Process this request!”
Built-in Handlers
If we look at the most important HttpHandler, the System.Web.UI.Page class (yes, the same one that all your pages inherit from), we really start to get a good feel for what an HttpHandler is responsible for. Looking at the internals of the Page class and starting from the ProcessRequest function, we quickly get to a ProcessRequestMain function which really starts to interact with stuff you do on a daily basis. Look at some of the stuff that happens in ProcessRequestMain:
...
base.InitRecursive(null);
if (context1.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End Init");
}
if (this.IsPostBack)
{
if (context1.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin LoadViewState");
}
this.LoadPageViewState();
if (context1.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End LoadViewState");
this.Trace.Write("aspx.page", "Begin ProcessPostData");
}
this.ProcessPostData(this._requestValueCollection, true);
if (context1.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End ProcessPostData");
}
}
base.LoadRecursive();
...
As you can see, it’s this method that’s responsible for causing all those ASPX events, such as OnInit and OnLoad, to be raised. In essence, the Page class does what it’s supposed to do: it’s handling the request.
Another handler we saw listed above is the HttpForbiddenHandler (which is a straight handler as opposed to a HandlerFactory). A number of paths are mapped to this handler – generally files that might compromise a security risk if left publically accessible (like .config, .cs, .vb, .dll, …). The ProcessRequest for this handler is to the point:
public void ProcessRequest(HttpContext context)
{
PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_NOT_FOUND);
throw new HttpException(0x193, HttpRuntime.FormatResourceString("Path_forbidden", context.Request.Path));
}
Why use a handler?
There are likely few times where you have to use a handler. Almost anything you can do in a handler, you could simply create an aspx page to take care of. So why bother? There are two main reasons. First and foremost, HttpHandlers are far more reusable/portable than pages. Since there’s no visual element to an HttpHandler (no .aspx), they can easily be placed into their own assembly and reused from project to project or even sold as is. Secondly, the Page handler is relatively expensive. Going with the “Hello World” examples, if you do that in a page you’ll end up raising a number of events (onInit, onLoad, onPreRender, onUnload, …) and make use of a number of ASP.NET features such as viewstate and postback. In most cases, the performance hit is negligible, but it nonetheless highlights that you’re using the page framework when you have no need to.
Real Examples
The first example to look at is the TrackbackHandler than’s part of CommunityServer 1.1. If you go to http://code.communityserver.org/ and open 1.1/Blogs/Components/TrackbackHandler.cs you’ll see the relevant source code. The purpose of this handler is to track pingbacks made to blog entries. Most blog engines will automatically send a pingback to any linked posts. This means that blog engines must also have a way to capture these pingbacks and record them. There’s more or less a standard between how the communication is supposed to happen, but each blog engine is really on its own as far as implementation. Without spending too much time in the code, we can see that the handler looks for a number of POST parameters and creates the trackback based on what’s passed in.
There’s absolutely no reason why all of this couldn’t be done using an ASPX page. But as I’ve already mentioned, that would force the entire ASPX page framework to be invoked. Additionally, this handler doesn’t even have a visual element – so a page doesn’t make too much sense.
(you can look at the web.config to see how the handler’s added).
Another example is my open source AMF.NET project which makes it possible for a Flash application to communicate with server-side ASP.NET code. The AmfGetwayHandler deserializes the AMF input (AMF is a proprietary binary protocol used by Flash), executes the right server side .NET function and returns a serialized response. Again, a single ASP.NET page could be used to accomplish the same thing, but then it would be impossible to package AMF.NET as a single assembly.
Another common example you’ll run across is using HttpHandlers to generate RSS feeds. Many applications will map “Rss.aspx” to an HttpHandler which generates a XML feed.
Why not to use HttpHandlers
The biggest and very significant drawback of HttpHandlers is that they can only be used for extensions that are mapped to ASP.NET in IIS. It might be great to create a file download counter for your .zip files using an HttpHandler, but since IIS doesn’t go through ASP.NET to serve .zip files, it isn’t going to work. One solution is to map those extra extension to ASP.NET, but that might have undesirable side effects and might not even be possible for you (many developers don’t have direct access to IIS). In this case, the only solution is to create an ISAPI filter which is much more difficult. IIS 7 promises to let us write ISAPI filters in .NET (or extend HttpHandlers beyond the ASP.NET pipeline depending on how you look at it), but that’s still a ways away.
Posted
05-24-2006 9:56 PM
by
karl