Saturday, February 27, 2010

ASP.net - Http handlers - Generic Hander

An HTTP Handler is a .NET class that executes whenever you make a request for a file at a certain path. Each type of resource that you can request from an ASP.NET application has a corresponding handler.

When you request an ASP.NET page, the Page class executes. The Page class is actually an HTTP Handler because it implements the IHttpHandler interface. Other examples of HTTP Handlers are the TraceHandler class, which displays applicationlevel trace information when you request the Trace.axd page and the ForbiddenHandler class, which displays an Access Forbidden message when you attempt to request source code files from the browser.

Similarly you can create your own HTTP handlers for acting on any requests received at webserver.

Generic Hander

Add a generic handler by right clicking on the project explorer > Add> new item> select Generic Handler.

A new file with ASHX extension is created.


Here is a sample code which I got from Steven Walthers book. This handler creates image dynamically based on the QueryString value received

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ImageTextHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            // Get parameters from querystring
            string text = context.Request.QueryString["text"];
            string font = context.Request.QueryString["font"];
            string size = context.Request.QueryString["size"];

            Font fntText = new Font(font, float.Parse(size));

            Bitmap bmp = new Bitmap(10, 10);
            Graphics g = Graphics.FromImage(bmp);

            SizeF bmpsize = g.MeasureString(text, fntText);
            int width =(int) Math.Ceiling(bmpsize.Width);
            int height = (int)Math.Ceiling(bmpSize.Height);
            bmp = new Bitmap(bmp, width, height);
            g.Dispose();

            // Draw the text
            g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            g.DrawString(text, fntText, Brushes.Black, new PointF(0, 0));
            g.Dispose();

            // Save bitmap to output stream
            bmp.Save(context.Response.OutputStream, ImageFormat.Gif);

        }

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

ProcessRequest() method is responsible for outputting any content that the handler renders to the browser.


The handler also includes an IsReusable property. The IsReusable property indicates whether the same handler can be reused over multiple requests. You can improve your application’s performance by returning the value True. Because the handler isn’t maintaining any state information, there is nothing wrong with releasing it back into the pool so that it can be used with a future request.


How can I use this generic handler?

You can put the following code in any ASPX file

<img src="ImageTextHandler.ashx?text=Hello World&font=WebDings&size=20" />
<br />
<img src="ImageTextHandler.ashx?text=Hello World&font=Comic Sans MS&size=20" />
<br />
<img src="ImageTextHandler.ashx?text=Hello World&font=Courier New&size=20" />


You will get a browser output like the following
The basic idea here is not to show how to create a image file on the fly but the handling of request by ASHX file


Post a Comment