Thursday, January 20, 2011

Create a Custom HTTP Handler

We know that all ASP.NET requests are mapped to corresponding HTTP handlers based on the file extension requested in the request. Also we have seen couple of HTTP handlers out of the box provided by ASP.NET such as Page handler (.aspx) , Usercontrol handler (.ascx), Webservice handler (.asmx) etc.

In order to build some additional handling functionality, we are requested to build some custom HTTP Handlers. We can implement two types of handlers basically by overriding the respective interfaces. We have IHttpHandler and IHttpAsyncHandler to create custom synchronous and asynchronous handlers respectively. The interfaces require us to implement ProcessRequest method and a property called IsResusable. ProcessRequest method is used to perform the logic to handle the request and IsReusable property can be set to true or false to decide whether to pool the handler for reuse.

Now let’s walk through on the steps required to create a Custom handler

· Create a Class Library Project. (in my case its “MyCustomHTTPHandler”) in Visual Studio 2008/2010.

· Add a class called “MyHandler.cs” and inherit from IHttpHandler. Make sure to add System.Web.dll reference.

· Now implement the method ProcessRequest and IsReusable property as well.

We can add necessary code logic inside the ProcessRequest to perform custom actions. We are now done with the coding. Now we need to add reference in Web.config for the handler under section in IIS 6.0 and in IIS 7.0/7.5. Also we need to configure it in IIS as well.

Here in this example you can add the following entry onto the web.config as follows

<add verb="*" path="*.sample" validate="false" type="MyCustomHTTPHandler.MyHandler"/>

So when a request comes for a resource with .sample extension, this referred handler gets fired.

You can download the source code for this sample from the following location. Click to download

No comments:

Post a Comment

Installing ASP.NET MVC

Installing ASP.NET MVC Before we dive deep into the ASP.NET MVC, let’s install it our development machine. This is very straight forwa...