Asp.Net Http Handlers (Part 1)

In the last instalment we discussed the need and motivation behind http handlers. We also discussed the creation and deployment of http handlers using ISAPI specification. In this section we will discuss how we can implement Http Handler using .net framework.

Before we talk about ‘how’  lets first talk about ‘what’  and ‘why’. Although we have already discussed about Http Handlers let us re-define from a different perspective.

Http handlers are programs that are invoked by a web server to get particular job done. period.

Now this job can be as big as implementing a whole new programming infrastructure or as small as printing a hello world message.

Let us also now discuss the possible meaning of an asp.net http handler. By extending the above definition we can easily deduce:

.Net Http Handlers are .net programs that will be invoked by the web server to get some job done.

But then, we already have facility to write a .net application (.aspx page) to get job done. So why do we need a new application? Why not just use a .aspx page? Let us try to understand this part with a sample application.

 

Why .net HTTP Handlers?

Let us try to answer this question by discussing a scenario:

Job Description: We need to create a image generator. The Image Generator can generate a given text into an image on the fly. Such images can be used for generating CAPTCHA or creating graphs based on the data present in database or creating an image of your email. The possibilities are endless.

Now that we know our job, let us try to find out what are the alternatives:

 

Create a .aspx page

 

Let us say we can create an imagegen.aspx to handle the situation. User can generate the image by invoking it with right set of parameters example:

http://dev.vnc.in/imagegen.aspx?type=text2img&text=dev@vnc.in&font-size=12&color:blue

This approach will work. However, there are several problems:

  • The page need to be incorporated in every website. A .aspx page is typically not considered as a component module. While same .aspx page can be included in several different website; it is not a very elegant pattern.
  • Although not explicitly stated, .aspx page is typically used for generating .html output. It is evident from the fact that a .aspx page is designed as a web page. Code behind is an optional entity. While it can generate an image; it is certainly not  a very clean solution.
  • Implementing a complicated set of steps in a single .aspx page goes contrary to the best coding practices. Over a period of time such pages will become unmanageable.
  • Because a .aspx page can’t serve all sorts of  purpose .net came up with other extensions such as .asmx.

While a .aspx page can be used for writing any kind of logic; it is neither the design goal nor a good practice us a .aspx page for roles other than generating a web output. This is clear from the fact that Microsoft itself came up with other extensions such as .asmx for web service.

It appears we have two options – wait for Microsoft to come up with a solution for my problem or we come up with our own customized solution.

 

I am sure you are not going to wait for Microsoft to come up with some solution. Are you?

 

If you are thinking in terms of our customized solution; it implies you are thinking about a HTTP Handler

Ok So we need a HTTP handler. But then we already have an infrastructure to create and deploy and HTTP Handler – ISAPI HTTP Handler.  We can use it. Isn’t it?

 

Why not an ISAPI Http Handler?

 

Sure. ISAPI seem to be an appropriate solution for creating an HTTP Handler. After all it exists with the sole purpose of creating an Http Handler. But then it is not really a .net based solution. Is it?

ISAPI is a win 32 dll and the handlers are typically written in C/C++ or other programming languages. The ISAPI don’t support extensive .net API. And a .Net developer need to master a new language to write a Handler.

Of the two choices – ISAPI  vs .aspx ; developer often choose easier and not so good approach – writing an .aspx page.

 

Having discarded the two alternatives, we are left with the only obvious choice – .net based HTTP Handlers. Let us try to understand why .net http handlers makes sense:

 

An asp.net http handlers are http handlers written in .net. It utilizes the full capacity of .net API and is an easier solution for a .net developer. It uses the best of both the worlds – ease of Handler coupled with convenience of .Net.

 

Implementing HTTP Handler in .Net

 

Having convinced ourselves about the benefit of a .Net Http Handler, let us understand the steps needed for implementing a .Net based Http Handler.

 

 

Step 1 – Creating The Handler

Creating the Handler is a simplicity in itself. All We need is to create a class that implements System.Web.IHttpHandler interface. The Interface has got just two methods. The following class diagram represents our ImageHandler and its relation with IHttpHandler.

IHTTPHandlerImplementation

 

 

Typically an Http Handler will be created as a class library. We also need to add a reference to System.Web assembly.

 

Let us create a class library. Name it vnc.web.ImageGenerator

Create-ImageGeneratorProject

Now Add the necessary System.web assembly.

add-ref

Change the project property to make the default namespace to vnc.web instead of vnc.web.ImageGenerator

change-project-property

Now delete the default class1.cs and add a new class – ImageGenerator.cs. Next implement interface System.Web.IHttpHandler.  Implement the Interface.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace vnc.web
{
    public class ImageGenerator: IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { throw new NotImplementedException(); }
        }

        public void ProcessRequest(HttpContext context)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

 

http://dev.vnc.in/app-name/red/black/georgia/12/vivek.jpg.image

Now let us go ahead and write our business logic. The business logic for the current ImageGenerator can be downloaded from the project and I am not including it here.

Compile the project to generate the necessary assembly. The Creation of HTTP Handler is complete.

 

Deploying the HTTP Handler

 

Now that the HTTP Handler is ready, let us focus on the deployment steps. It includes two steps:

 

Configuring IIS Handler Mapping

 

iis-config

Since our HTTP Handler is not an ISAPI Handler, it is not supposed to be registered directly in the IIS Handler Mapping as we discussed in the previous episode – Http Handlers (Although the latest IIS does have an option).  What we need to do is to map the new URL Pattern to asp.net engine. Now IIS will pass the request for new resource to aspnet_isapi.dll . (Ofcourse asp.net engine doesn’t know how to process this request. But we will handle this in a separate step)

 

 

 

 

Now all request for the .image extension will be diverted to aspnet_isapi.dll – The Asp.net engine. However, predictably, asp.net has got no idea as to how to handle this request or whom to pass this request. This configuration will be done in web.config or mechine.config depending on the requirement.

 

Registering Our Handler with asp.net

 

To configure asp.net engine to pass request for .image resources to our handler we need to register our handler in web.config or machine.config. We need following steps:

  1. Add a Test website to our solution
  2. Add a reference to the website project. Select the vnc.web.ImageGenerator.dll assembly from the list.
  3. Add handler reference to web.config. Locate handler section and add the code as mentioned below. Look up for a Handler section and add following entry. The code has been modified for clarity
<httpHandlers>
       <remove verb="*" path="*.asmx"/>
       <add verb="*" path="*.asmx" validate="false" … >
<add verb="*" path="*_AppService.axd" validate="false" type="…” /> <add verb="GET,HEAD" path="ScriptResource.axd" type="…”/> <add verb="*" path="*.image" type="vnc.web.ImageGenerator"/> </httpHandlers>

 

The newly added entry has been underlined. Now we are done and we can test our application safely.

try out running following url

http://localhost:47877/HandlerDemoSite/red/black/georgia/22/Vivek%20Dutta%20Mishra.jpeg.image

And you should get a jpeg image generated for you with your choice. The given path doesn’t exist physically and yet it will return the result.

In our next instalment, we will discuss some other advanced features of asp.net http handler.

 

Download File – ImageGeneratorSolution

Http Handlers

This is a continuation of our series on HTTP. This Articles discusses the motivations and design concerns related to creation of Handler. The articles covers the technical details of what we discussed in the preceding article  Http Hacked.

Before we attempt to understand the concept of handlers we need to understand the working of HTTP. I would recommend going through the previous articles for this purpose:

  1. story of www – between http and html – This is the main article that discusses the evolution of www, http protocol. Its motivation and the road map.
  2. Http HackedThe most important article to understand the current discussion. This is the second instalment on the running story on http. The episode mainly discusses how http was hacked for web programming.
  3. Http Through Ages – This article is a technical overview of the changes between various versions of http and you may like to go through it for the completion of discussion.

Now lets quickly recap how an Http Server works.

 

Scenario 1. Http Server is requested to Serve a static resource

By static resource we mean a html document or an image or a downloadable content that always exists (or can exist) on the server, and all a server does is to pick it and pass it to the client. The following diagrams represents the scenario:

Http-Request-Response-Model

Any and every Http Server is designed to serve this kind of request. As such the request is handled in strict accordance with http protocol.

 

Scenario 2. Http Server is requested a Dynamic Resource

The situation get trickier when you need to serve a resource that doesn’t exist; rather it is created. More accurately – that is computed. An example could be – requesting a list of customers. The information exists in the database. It needs to be extracted and presented in a tabulated format. So we need a program that –

  • Accepts users request and relevant parameters
    • Parameter may tell to get a list of priority customer
    • Filter customers based on geographical location and so on
  • Executes relevant queries on to the database and extracts the necessary records
  • Creates an HTML page with the extracted records in a presentable format.
  • Sends the newly created html page to the user.

So we need a program. But how does this program relate to the web server. Web server need to delegate its work to this special program which is designed to handle the request. The overall interaction process is represented in following diagram:

 

Http-Request-Response-2

 

The diagrams brings out following points clearly:

  1. Web server really doesn’t know how exactly to use the dynamic resource (in our case customer.aspx)
  2. It relies on an external application or extension to get the computation done. These extension are typically termed as http handlers.
  3. A web server typically can delegate the computation to one of the many handlers.
  4. Each Handler is supposed to process a particular kind of request which can be identified by url format.
  5. A url format may mean
    1. In most of the cases a particular extension  – *.asp, *.aspx, *.php, *.jsp and so on
    2. It may also mean request associated with a particular folder. Eg. /cgi-bin/*
    3. It may be a particular absolute path – Eg /log/log.app
  6. The web server checks the Url and then decides whom to delegate the request.

 

Developing The Handlers

 

As we already discussed in our previous article Http Hacked, that the need of such an extension was felt clearly. We needed a mechanism to extend the server in different and unpredictable ways. For this reason different vendors proposed their solution. The solutions had implementation differences, however, philosophically they had same working principle:

Define a set of guidelines and  API that will be used for creating a handler. The Handler will expose a certain well defined set of functionality that will be called by the web server to get the request processed.

Microsoft proposed an API layer and termed it as ISAPI – Internet Server API

Netscape, for example, proposed NSAPI – Netscape Server API.

 

Servers and handlers are supposed to be compliant with one of the available standards. For example IIS is an ISAPI compliant server and can work with any ISAPI  compliant handler. All ISAPI compliant handlers are supposed to work with every ISAPI compliant servers.

 

An ISAPI handler is typically written as a win32 dll and is designed in C/C++ language. However, other language choices are also available.

 

Deploying the Handler

Once a Http Handler is created, it needs to be registered with the web server and mapped with an url pattern. Following screenshots shows different ISAPI handlers registration with IIS 7.0.

Step 1: Start Internet Service Manager from Control Panel –>Administrative Tools

 

Step 2: Navigate to Http Handler Mapping section

isapi handler configuration 1

 

Step 3: We will have a list of existing mapping. We can modify them or add new entries

isapi handler configuration 2

 

Step 4: This is a sample mapping of .aspx files to aspnet_isapi.dll

 

isapi handler configuration

 

 

Summary

 

In this section we looked at the roles of Http handlers and their deployment. In the next episode we will be checking deployment of http handler using asp.net.