CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
HttpHandler in ASP.Net - PART 2

By Satheesh Babu
Posted On Feb 24,2008
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 16
Category: ASP.Net
Print this article.

In this article, I will elaborate implemention of custom httphandlers and the scenarios we can use it. It is a .Net component that implements System.Web.IHttpHandler interface.HttpHandlers can be implemented in 2 ways,

 

  • Synchronous HttpHandler
  • Asynchronos HttpHandler

 

A Synchronous HttpHandler should implement System.Web.IHttpHandler interface while an asynchronous HttpHandler should implement System.Web.IHttpAsyncHandler. I will concentrate on implementation of Synchronous HttpHandler in this article. We will first explore about IHttpHandler and its members.

ProcessRequest()

            This method is the core of HttpHandler as it does all the processing of an HttpHandler.

IsReusable

            This property specifies whether the HttpHandler can be reused for similar request.

 

So the HttpHandler implementation should contain implementation of both the members.

 

Where to use?

I will explain a sample scenario where we can use the HttpHandler in a normal application. Assume that we are developing an application that deals with lots of images and the complication is when we have to display the entire images in the database i.e. in BLOB. To display it in a page we need to construct a new page which fetches the image from database and do a BinaryWrite .i.e. the final code will be like,

 

  imImage.ImageUrl = "~/ImageHandler.aspx?ImID=100;

 

Where imImage is image control and ImageHandler.aspx will have the code,

 

string imageid = context.Request.QueryString["ImID"];

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);

connection.Open();

SqlCommand command = new SqlCommand("select Image from Image where ImageID="+imageid, connection);

SqlDataReader dr = command.ExecuteReader();

dr.Read();

context.Response.BinaryWrite((Byte[])dr[0]);

connection.Close();

context.Response.End();

 




If we consider the above scenario to use an ASPX page to fulfill a single database operation where the other page events are not necessary i.e. the ASPX page will have a series of event starting from Init to Unload which is an overhead to this simple database operation. One can understand the complexity if we are trying to populate more images in a single page using the above approach. It is in this place we can think about using HttpHandler to do the above process. As we know the HttpHandler will be the endpoint for the request as opposed to the above ASPX page. Now the HttpHandler will have only one method ProcessRequest which does the simple operation and thus preventing a series of events. So how does the ProcessRequest method get the access of Response object? If we see the signature of ProcessRequest it will be like,

 

public void ProcessRequest (HttpContext context)

{

}

 

The context object will give access to necessary object about the request. It is through which we can do a BinaryWrite using Response object. Other scenarios where we can use HttpHandler is, if we want to export the dataset content to Excel and if we want to have a file with our own extensions like .axd we can use HttpHandler. We have to make appropriate config setting in Web.Config to work,

<httpHandlers>

       <add verb="supported http verbs" path="path" type="namespace.classname, assemblyname" />

<httpHandlers>

Where verb are “GET, POST”, path will be like “*.axd” for the above said example and type will be the actual type of the handler.

 

Developing a HttpHandler using Visual Studio 2005

 

Create a new WebApplication project. Right click the solution and click “Add New Item” menu which will open the new items dialog box like,

 

 

Select Generic handler and click Add. Now add the following code,

<%@ WebHandler Language="C#" Class="ImageHandler" %>

 

using System;

using System.Web;

using System.Configuration;

using System.Data.SqlClient;

 

public class ImageHandler : IHttpHandler {

   

    public void ProcessRequest (HttpContext context) {

        string imageid = context.Request.QueryString["ImID"];

        SqlConnection connection = new         SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);

        connection.Open();

        SqlCommand command = new SqlCommand("select Image from Image where ImageID="+imageid, connection);

        SqlDataReader dr = command.ExecuteReader();

        dr.Read();

        context.Response.BinaryWrite((Byte[])dr[0]);

        connection.Close();

        context.Response.End();             

       

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

 

}

To display the image in ASPX page,

 

  imImage.ImageUrl = "~/ImageHandler.ashx?ImID=100;

 

Where imImage is image control and ImageHandler.ashx is the HttpHandler.

The output will be like,

 

 

Download Source:

Download
Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
imageID as varchar
I am getting some error maybe due to having the imagID as varchar(50) and not int, what need to be changed in the code to make it work with imageID as varchar?

Thanks
thanks
very good article fore read and write imege from Database
Mr
Very nicely written article.

Thanks
Superbbbbbb
A very nice and Very Clear Http Hanlders in details....
a lot of Thanks.
Knowledge Stuff
I have come across this article and its a must read article, will give you good use of HTTPhandler and its customization.

Thanks Satheesh Babu
saveImage
I was run by using this source code. Very nice article. It is very useful my project. I was learn from this article.


Thanks &Regards

M.Masanamoorthy
Cool Stuff
Lovely article... Explained in neat manner :-)
Nice article
Nice article to learn basic about IHttpHandler
Good article
Good article. Gives a clear understanding without too much detail. English could use a little tweaking but basically good.
Very Nice article
It is very nice article and also addressed purpose of HttpHandler in asp.net
Rajesh B Patil
Thank you for the wonderful article, this is the first time i really followed the custom handlers, Thanks again, keep up the good work.
Convert to VB.NET
I am converting your C# code to VB so I can test it. But I am having problem on converting this line "context.Response.BinaryWrite((Byte[])dr[0]);" My VS 2005 does not take Byte saying it is a "type and cannot used as an expression". Please help. Much appreciated!
RE:Image Not Shown
Hi, Sorry its my fault. It workz fine :) ThanX
Image Not Shown
Hi, I tried implementing the your code. Things are fine except image not being shown. Any suggestion ? ThanX :)
RE:Good one.
sorry for missing the source..its available now!
Good one.
Needs some more clarity in this part. Also please provide Sourc code also. http://www.anurakti.com/