Home > Articles > Programming > Windows Programming

This chapter is from the book

HttpHandlers

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

HttpHandler

Purpose

PageHandlerFactory

Processes .aspx pages.

WebServiceHandlerFactory

Processes .asmx XML Web services.

HttpForbiddenHandler

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.

StaticFileHandler

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

TraceHandler

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("<HTML><BODY>");
      context.Response.Write("Hello from SimpleHandler");
      context.Response.Write("</BODY></HTML>");
      }
  
    public bool IsReusable
      {
      get 
        {
        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, 
elements
    public void ProcessRequest(System.Web.HttpContext context)
    {
      System.IO.FileStream fs = null;
      SqlConnection cn = null;

      try
      {  
        // 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
        cn.Open();
        // 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
        strBuff.Append("<results>");
        // Get all the rows
        while(dr.Read())
        {
          strBuff.Append(dr.GetString(0));
        }
        // Add the ending element
        strBuff.Append("</results>\r\n");
        // Close the connection
        cn.Close();
        // Load XML into document
        System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
        // Load it up
        xd.LoadXml(strBuff.ToString());
        
        // 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 
System.Xml.XmlTextReader(fs));
        
        // Close the file
        fs.Close();

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

        // 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 + 
"</html></body>");
      }
      finally
      {
        // Close the file stream
        if(fs!=null) fs.Close();  
        // Close the db connection
        if(cn!=null) cn.Close();
      }

    }

    public bool IsReusable
    {
      get
      {
        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>
  <xsl:template match="/*">
    <html><body>  
    <Table WIDTH="100%" BORDER="1" topmargin="0" leftmargin="0" 
          cellpadding="0" cellspacing="0">
      <xsl:for-each select="./*">
        <tr>
          <xsl:for-each select="./*">
            <td>&#160;
                        <xsl:value-of select="." />
                       </td>
          </xsl:for-each>
        </tr>
      </xsl:for-each>
    </Table>
    </body></html>
  </xsl:template>
</xsl:stylesheet>

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:

http://localhost/book/handlemod/handlers/tableviewer.xsql
    ?sql=select%20*%20from%20authors%20for%20xml%20auto,%20elements

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.

NOTE

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;

      if(hPageCounter.Contains(strUrl))
      {
        // 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;
      }
      else
      {
        // 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
      g.Clear(System.Drawing.Color.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);
      g.Flush();

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

    public bool IsReusable
    {
      get
      {
        return true;
      }
    }
  }
}

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020