Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book


Whereas HttpModules are designed to participate in the processing of a request, HttpHandlers are designed to be the endpoint for the processing of a request. As mentioned earlier, an HttpHandler provides a way to define new page processors that handle new types of programming models. Table 8.1 shows the HttpHandlers provided by ASP.NET.

Table 8.1—Built in ASP.NET HttpHandlers




Processes .aspx pages.


Processes .asmx XML Web services.


Yields an error message indicating that a type of page is not in service. By default all .asax, .vb, .cs, .ascx, .config, .csproj, .vbproj, .webinfo files are mapped to this in machine.config.


Delivers any page that isn't specifically mapped, such as .html, .htm, and .jpg.


Shows the page containing all of the trace output.

ASP.NET provides different handlers for ASP.NET pages and Web services. Each knows how to handle the files associated with the extension appropriately. HttpHandlers don't have to be backed by files, however. ASP.NET allows the HttpHandler to provide the entire response to a request. Listing 8.13 shows a very simple HttpHandler that displays a Hello World type of page.

Listing 8.13—Hello World from an HttpHandler

using System.Web;

namespace Handlers 
  public class SimpleHandler : IHttpHandler 
    public void ProcessRequest(HttpContext context)
      context.Response.Write("Hello from SimpleHandler");
    public bool IsReusable
        return true;

This code implements the IHttpHandler interface, which describes only one method and one property. The IsReusable property lets ASP.NET know if it can reuse an instance of an HttpHandler or if it needs to re-create it from scratch each time. The ProcessRequest() method is called to do the work of the HttpHandler. In our simple handler, we output a very trivial HTML page that writes a message to the browser.

To get this simple handler to work, you need to do two things. First, you need to add a new application mapping to map an extension to ASP.NET. This mapping is required to make sure that IIS calls ASP.NET when it receives a request for a page with that extension. Without the mapping, ASP.NET is never invoked, and unless the HttpHandler happens to have a matching page, you will receive a 404 Not Found error.

To add a new application mapping, perform these steps in the Internet Services Manager.

  1. Select the application root of your application in Internet Services Manager.

  2. Open the Property page.

  3. Select the Directory tab

  4. Click the Configuration button

  5. Select the App Mappings tab

  6. Click the Add button and create an application mapping to aspnet_isapi.dll for the extension you are interested in. For this example, define the extension as .hello

The next step is to modify the web.config or machine.config files to map the extension to the class you have created. The <httpHandlers> section of web.config defines the handlers that ASP.NET will load. By adding a single line like the following:

<add verb="GET" path="*.hello" type="handlers.SimpleHandler, handlers" />

ASP.NET will now call your HttpHandler whenever a page with the extension .hello is called. Note the verb attribute. This indicates for which HTTP/1.1 verbs the action will be performed. Valid verbs include GET, PUT, and POST. If you want to handle any type of request for that URL, you can use a wildcard of *.

After all these steps are complete, whenever the user types a URL ending in .hello at any path within the application root, SimpleHandler will get called. If no files exist in the application root, all of the following URLs are valid:

  • http://localhost/book/handlemod/handlers/junk/asdfa/asdfas/WebForm1.hello

  • http://localhost/book/handlemod/handlers/WebForm1.hello

  • http://localhost/book/handlemod/handlers/.hello

The resulting output is the very simple HTML page provided by the handler.

Dynamic Reporting

The next sample is going to do something a little more involved, combining SQL and XML. SQL Server 2000 is able to output data as XML and XSL, making a powerful combination. Let's write an HttpHandler that handles a new file extension, .xsql. In this case there will actually be physical .xsql files on disk. These files are just the XSL templates that should be applied to the XML output from SQL Server. Our handler will expect each request to these files to include a SQL parameter. This parameter indicates the query that should be run and then merged with the XSL template. This combination allows us to run any SQL that can be output as XML and dynamically bind it to an XSL template. It's a pretty powerful concept.

Let's take a look at the code in the HttpHandler first. Listing 8.14 shows the SqlHandler.

Listing 8.14—SqlHandler Transforms XML SQL Queries from SQL Server with XSL Templates

using System;
using System.Data.SqlClient;

namespace Handlers
  /// <summary>
  /// Summary description for SqlHandler.
  /// </summary>
  public class SqlHandler : System.Web.IHttpHandler
    public SqlHandler()

    // Call like this
    // http://localhost/csharp/handlers/tableviewer.xsql=select * from authors for xml auto, 
    public void ProcessRequest(System.Web.HttpContext context)
      System.IO.FileStream fs = null;
      SqlConnection cn = null;

        // Get the sql
        string strSql = context.Request["SQL"];

        // Setup a DB connection
        cn = new SqlConnection("SERVER=localhost;UID=sa;PWD=;DATABASE=pubs;");
        // Open the connection
        // Create a command
        SqlCommand cmd = new SqlCommand(strSql, cn);
        // Get a data reader reference
        SqlDataReader dr;
        // Execute the sql
        dr = cmd.ExecuteReader();
        // Get a buffer
        System.Text.StringBuilder strBuff = new System.Text.StringBuilder("<?xml 
version=\"1.0\" encoding=\"utf-8\" ?>\r\n");
        // Encapsulate with root element
        // Get all the rows
        // Add the ending element
        // Close the connection
        // Load XML into document
        System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
        // Load it up
        // Attempt to open the xslt
        fs = new System.IO.FileStream(context.Request.PhysicalPath, System.IO.FileMode.Open);
        // Load it into a navigator
        System.Xml.XPath.XPathDocument xpn = new System.Xml.XPath.XPathDocument(new 
        // Close the file

        // Create a transform
        System.Xml.Xsl.XslTransform xslt = new System.Xml.Xsl.XslTransform();
        // Load it

        // Transform it to the output stream
        xslt.Transform(xd.CreateNavigator(), null, context.Response.Output);

      catch(Exception e)
        // Write an error message
        context.Response.Write("<body><html>Invalid xsql query<Br>Message: " + e.Message + 
        // Close the file stream
        if(fs!=null) fs.Close();  
        // Close the db connection
        if(cn!=null) cn.Close();


    public bool IsReusable
        return true;


Right at the beginning, wrap this code in a try/catch block. If any part of the code fails, it will write an error message back to the user indicating that a problem occurred with the query and including the exception text.

Next, grab the SQL parameter from the request object and use it to run a query against SQL Server. The HttpHandler expects that the SQL query includes the "for xml auto, elements" clause. Next the HttpHandler retrieves all the data from the query using a DataReader. The HttpHandler prepends and appends a root element because SQL Server does not create a unique root element by default. The HttpHandler reads only the first column because the for xml clause causes SQL Server 2000 to return a 1 column by N row result, in which each row contains a portion of the string 2033 characters or less in length. So, concatenate these fragments using a StringBuilder. Again, because strings are immutable, concatenation operations are expensive, requiring copying the string around in memory. For something like this where there could be a large number of concatenations, a StringBuilder makes more sense—it's very efficient to append text using a StringBuilder.

After all the data is loaded into the StringBuilder, go ahead and load it into an XMLDocument to prepare it for transforming. The next step is to load the actual XSL template. This was the URL that caused the HttpHandler to fire in the first place. Get its physical path using the PhysicalPath property of the request object, and then open it with a FileStream and load it into an XpathDocument via a XMLTextReader. Finally, an XSLTransform object is created, the XSL is loaded into it, and the transformation is performed. Pass the Response.Output property to the Transform method. This is a stream, which is one of the possible outputs for the Transform method.

Now we also need an XSL template. Listing 8.15 shows a generic XSL template that takes some XML and formats it as a table.

Listing 8.15—The XSL Template Used to Format the Output

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
   xmlns:msxsl="urn:schemas-microsoft-com:xslt" version="1.0">
  <xsl:template match="/">
    <xsl:apply-templates select="/*" />
  <xsl:template match="/*">
    <Table WIDTH="100%" BORDER="1" topmargin="0" leftmargin="0" 
          cellpadding="0" cellspacing="0">
      <xsl:for-each select="./*">
          <xsl:for-each select="./*">
                        <xsl:value-of select="." />

This template is generic XSL that could be used for almost any query. Before we can test these two items (Listing 8.14 and Listing 8.15), we have to add the .xsql application mapping in Internet Service Manager. As noted previously, this routes requests for .xsql files to ASP.NET. We also need to add an entry in web.config to map requests for .xsql files to SqlHandler. Finally, we can run the code. We need to specify a URL of the following form:


This includes the path to our XSL template as well as the URL-encoded SQL that we want it to run. The query contained in the preceding URL yields the output shown in Figure 8.4.

Figure 8.4 The output from our SqlHandler.


The preceding example is not incredibly secure since you have given a user a way to execute any arbitrary SQL on your server. This includes extended stored procedures and DDL.

Page Counter Handler

Graphical page counters were all the rage early on during the evolution of the Web, but it wasn't easy to create the images dynamically in ASP until now. The next example is an HttpHandler that can be called inside an image tag in any page, like this:

<img src="PageCounter.cntr">

As long as the HttpHandler is mapped, the path is irrelevant. Upon execution, the HttpHandler looks at the referrer to determine what page it is being displayed in. The referrer is used as the key of an internal hash table that contains the current page view count. (If you were to move this structure into production, you would need a more durable storage location than just a private hash table.) After the page view has been looked up, it is time to go to work. We get a new 1-pixel bitmap just so we can get a graphics object. Because we are doing this code in an HttpHandler, there is no "paint" method that comes with a pre-created object for us. By creating a 1-pixel bitmap, we can then obtain a graphics object for the bitmap. Next, we create a font. In this case, we are using a Verdana 14-point font, but the font specifics could passed on the command line to dynamically select a font.

Everything is now in place to measure the page count string. After we know the measurements, it is time to create a new bitmap of the appropriate size. The bitmap is cleared, anti aliasing is turned on, and the string is drawn into the new bitmap. We convert the bitmap to a GIF using the Save method. The final step is to stream it to the Response.Output stream after setting the ContentType to image/gif. Listing 8.16 shows the HttpHandler.

Listing 8.16—A Page Counter HttpHandler That Dynamically Generates Page Count GIF Files

using System;
using System.Drawing;

namespace SimpleHandler
  /// <summary>
  /// Summary description for PageCounter.
  /// </summary>
  public class PageCounter : System.Web.IHttpHandler
    // object to hold our counters
    private System.Collections.Hashtable hPageCounter = new System.Collections.Hashtable();

    public PageCounter()
      // TODO: Add constructor logic here

    public void ProcessRequest(System.Web.HttpContext context)
      int iPageCount = 1;
      string strUrl = context.Request.UrlReferrer.ToString();
      string strPageCount;

        // Get the page count and increment by 1
        iPageCount = (int) hPageCounter[strUrl] + 1;
        // Create a string of the page count
        strPageCount= iPageCount.ToString();
        // Update the page count
        hPageCounter[strUrl] = iPageCount;
        // Init the page count
        hPageCounter.Add(strUrl, 1);
        // Set the page count to 1
        strPageCount = iPageCount.ToString();

      // Create a new bitmap of minimum size
      Bitmap b = new Bitmap(1,1);
      // Get a graphics surface
      Graphics g = Graphics.FromImage(b);
      // Create a font
      Font f = new Font("Verdana", 14);

      // Measure the string so we know how wide to make it
      SizeF s = g.MeasureString(strPageCount, f);

      // Create the proper size bitmap
      b = new Bitmap((int)s.Width, (int)s.Height);
      // Get the grpahics surface again
      g = Graphics.FromImage(b);
      // Clear the background to white
      // Indicate antialiased text
      g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

      // Draw the page count on the bitmap
      g.DrawString(strPageCount, f, new SolidBrush(System.Drawing.Color.Black), 0, 0);

      // Output the graphic
      context.Response.ContentType = "image/gif";
      b.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);

    public bool IsReusable
        return true;

The end result is an image in the page containing the count of how many times the page has been viewed.

  • + Share This
  • 🔖 Save To Your Account