Click here to Skip to main content
15,117,318 members
Articles / Web Development / ASP.NET
Technical Blog
Posted 2 Feb 2013


11 bookmarked

The Truth About HttpHandlers and WebApi

Rate me:
Please Sign up or sign in to vote.
4.96/5 (12 votes)
3 Feb 2013Ms-PL5 min read
HttpHandlers had their place, but going forward, I'm going to use WebAPI whenever I need to transmit data over HTTP to browsers or any other connected client.

In 2012 when Microsoft introduced the ASP.NET WebAPI, I initially became confused about yet another way to generate and transmit content across a HttpRequest. After spending some time thinking about WebAPI over the past week or two and writing a few blocks of sample code, I think I finally have some clarity around my confusion and these are those lessons I learned the hard way.

Old School API - SOAP and ASMX 

When ASP.Net launched, the only framework to create and publish content that was available was WebForms.  Everybody used it, and it worked well.  If you wanted to create an interface for machine-to-machine communications you would create a SOAP service in an ASMX file.  You could (and still can) add web references to projects that reference these services.  The web reference gives you a first class object with a complete API in your project that you can interact with.

Over time, it became less compelling to build the SOAP services as they transmitted a significant amount of wrapper content around the actual payload you wanted to work with.  This extra content was messy, and other programming languages didn't have the tooling support to manage them well.  Developers started looking for less complicated alternatives to communicate with connected clients.  It turns out that there was another option available that was overlooked by many: HttpHandlers.

HttpHandlers in ASP.NET

HttpHandlers are the backbone of ASP.NET.  An HttpHandler is any class that implements the IHttpHandler interface, handles an incoming request, and provides a response to webserver communications. IHttpHandler is a trivial interface with the following signature: 

public class TestHandler : IHttpHandler
    public void ProcessRequest(HttpContext context)
        // TODO: Implement this method
        throw new NotImplementedException();

    public bool IsReusable
            // TODO: Implement this property getter
            throw new NotImplementedException();

Listing 1 - Simple IHttpHandler interface implementation

The ProcessRequest method is where we can insert our code to handle all data being requested of the handler and all data to respond from the handler. The IsReusable property is often misunderstood, but has a simple definition: Should an instance of this handler be re-used for other requests to the webserver?  If the return value is false, a new version of the handler class will be instantiated for each request to the server.  If IsReusable returns true, then the same instance will be used for all requests to the server.  A simple implementation that outputs some of my favorite sports teams in XML format might look like this:

public class MyHandler : IHttpHandler
    public readonly static IEnumerable<team> MyTeams = new List<team>
        new Team { City = "Philadelphia", Name = "Phillies" },
        new Team { City = "Boston", Name = "Red Sox" },
        new Team { City = "Cleveland", Name = "Browns" },
        new Team { City = "Houston", Name = "Astros" },
        new Team { City = "San Diego", Name = "Chargers" }

    #region IHttpHandler Members

    public bool IsReusable
        get { return true; }

    public void ProcessRequest(HttpContext context)
        context.Response.ContentType = "text/xml";


        foreach (var t in MyData.MyTeams)




Listing 2 - A Sample XML Generating HttpHandler

Some developers get confused about the difference between a class that implements IHttpHandler and an ASHX file.  These are very similar things, but different with their own advantages.  An ASHX file is an IHttpHandler whose end-point is defined by the name of the ASHX file.  If you create foo.ashx you can trigger the ProcessRequest method by navigating to http://localhost/foo.ashx  Conversely, a class that implements IHttpHandler needs to be registered in web.config with a path and file-extension end-point to answer to.  The format of this registration lies within the system.webServer section of web.config


    <add name="MyHandler" path="*.my" verb="GET"          
            type="WebApplication2.MyHandler, WebApplication2" />  


Listing 3 - Web.Config entries for an HttpHandler

Further instructions on how to configure the HttpHandler is available on MSDN

Both of these types of HttpHandlers are easy to implement, and put you right on the metal.  You are handed and HttpContext and you can do anything you want to handle the incoming request and respond to it.  If you are working with some low-level operations such as inspecting HttpHeaders for responses, you may choose to go this route.

ASP.NET WebAPI in a nutshell

Scott Guthrie describes ASP.Net WebAPI as a technology that allows developers to build powerful web based APIs that have the following 9 core capabilities:

  • Modern HTTP Programming Model - Directly access the HTTP requests and responses using a strongly typed HTTP object model
  • Content Negotiation - Built in support for content negotiation, which allows the client and server to work together to determine to correct data format to return from an API
  • Query Composition - Easily supports OData URL conventions when you return a type of IQueryable<T> from a method
  • Model Binding and Validation - Supports the same model binding available in WebForms and MVC
  • Routes - You know 'em, you love 'em... they're all over ASP.Net.  Why WOULDN'T you expect them in WebAPI?
  • Filters - You can apply similar filters to those that you create for MVC
  • Improved Testability - WebAPI uses two new objects called HttpRequestMessage and HttpResponseMessage to make unit testing significantly easier.  
  • IoC Support - The same service locator pattern implemented in ASP.Net MVC is available to inject dependencies into your API implementations
  • Flexible Hosting - Web APIs can be hosted within any type of ASP.NET application.  You can also host it within any process if you don't want to engage IIS to host your API.

The quick and dirty summary of this list is that WebAPI functions, looks, and feels like developing with ASP.Net MVC.  There are a few simple differences between them, but once you learn them, its very easy to progress quickly.

The Super-Duper Happy Sample

To implement a simple service that outputs a collection of values when a GET is called with no arguments (eg: http://localhost/api/Values ) you need to add very little to get started.  First, add a WebAPI controller to your website by selecting the appropriate item in the Add Item dialog box:

Image 1 - Add WebAPI Controller

The default implementation delivered looks like the following:

public class ValuesController : ApiController
    // GET api/<controller>
    public IEnumerable<string> Get()
        return new string[] { "value1", "value2" };

    // GET api/<controller>/5
    public string Get(int id)
        return "value";

    // POST api/<controller>
    public void Post([FromBody]string value)

    // PUT api/<controller>/5
    public void Put(int id, [FromBody]string value)

    // DELETE api/<controller>/5
    public void Delete(int id)

Listing 4 - Default API Controller implementation

With this simple implementation you can navigate your browser to http://localhost/api/values and get the two values "value1" and "value2" returned in XML format.  If you programatically request that address and change your "accept" header to "text/json" you will receive JSON in the response stream.  You can PUT, POST, and DELETE content to this controller and the appropriate action methods will be triggered based on the HTTP action executed.  

The Truth

WebAPI is just another HttpHandler, one that has been wrapped around all sorts of helpful content management and negotiation technologies as Scott Guthrie suggested.  You certainly could cut out all of those other technologies and benefits and code directly "on the metal" with an HttpHandler, and that was the only choice you had until 2012 and ASP.NET 4.  In today's web community, it is best to use RESTful methods and use a standard format like XML or JSON to transfer data.  HttpHandlers had their place, but going forward, I'm going to use WebAPI whenever I need to transmit data over HTTP to browsers or any other connected client.

This article was originally posted at


This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


About the Author

Jeffrey T. Fritz
Program Manager
United States United States
Jeff Fritz is a senior program manager in Microsoft’s Developer Division working on the .NET Community Team. As a long time web developer and application architect with experience in large and small applications across a variety of verticals, he knows how to build for performance and practicality. Four days a week, you can catch Jeff hosting a live video stream called 'Fritz and Friends' at You can also learn from Jeff on WintellectNow and Pluralsight, follow him on twitter @csharpfritz, and read his blog at

Comments and Discussions

QuestionCan we achieve "fire and forget" behavior using webapi the same way as with ashx Pin
Member 1094793315-Jan-15 7:54
MemberMember 1094793315-Jan-15 7:54 
QuestionNice explanation my vote of 4 Pin
chait30121-Sep-14 5:48
Memberchait30121-Sep-14 5:48 
GeneralMy vote of 1 Pin
Azeem Raza Tayyab20-Jun-14 0:41
MemberAzeem Raza Tayyab20-Jun-14 0:41 
QuestionHow does it leverages HTTP requests better than handlers ? Pin
PhaniKatakam8-May-13 4:18
MemberPhaniKatakam8-May-13 4:18 
AnswerRe: How does it leverages HTTP requests better than handlers ? Pin
Jeffrey T. Fritz8-May-13 5:42
sponsorJeffrey T. Fritz8-May-13 5:42 
WebAPI provides a wrapper around the Http request object, giving you the high-level abstraction to work directly with your classes. HttpHandlers are very low-level and give you direct access to every byte sent over the wire in each direction. You have tremendous control over the HttpHandler's input and output, but you need to do a lot of work on your own to format and translate that content into a richer object set.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.