Click here to Skip to main content
Click here to Skip to main content
Go to top

The Truth About HttpHandlers and WebApi

, 3 Feb 2013
Rate this:
Please Sign up or sign in to vote.
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
    {
        get
        {
            // 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";

        context.Response.Write("<teams>");

        foreach (var t in MyData.MyTeams)
        {
            context.Response.Write("<team>");
            context.Response.Write("<city>");
            context.Response.Write(t.City);
            context.Response.Write("</city>");
            context.Response.Write("<name>");
            context.Response.Write(t.Name);
            context.Response.Write("</name>");
            context.Response.Write("</team>");
        }

        context.Response.Write("</teams>");

    }

    #endregion
}

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

<system.webserver>
<handlers>

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

  </handlers>
</system.webserver> 

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.

License

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

Share

About the Author

Jeffrey T. Fritz
Telerik
United States United States
A Microsoft MVP, ASPInsider and ASP.NET Developer Evangelist for Telerik. Jeffrey is a software developer coach, architect, and speaker in the Microsoft.Net community. A Pluralsight author and international speaker, Jeffrey makes regular appearances at conferences such as TechEd, DevIntersection, CodeStock, FalafelCon, DevReach and New York Code Camp as well as user group meetings in an effort to grow the next generation of software developers
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionNice explanation my vote of 4 Pinmemberchait30121-Sep-14 4:48 
GeneralMy vote of 1 PinmemberAzeem Raza Tayyab19-Jun-14 23:41 
QuestionHow does it leverages HTTP requests better than handlers ? PinmemberPhaniKatakam8-May-13 3:18 
AnswerRe: How does it leverages HTTP requests better than handlers ? PinmemberJeffrey T. Fritz8-May-13 4:42 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140926.1 | Last Updated 3 Feb 2013
Article Copyright 2013 by Jeffrey T. Fritz
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid