This is the “HttpHandler and HttpModule in real scenerion” article series. As the name suggests, in this series we will understand a few real scenarios where we can use HttpHandler and HttpModule. In our previous two articles we have learned to implement simple HttpHandler in our ASP.NET application. You can read them here.
- HttpHandler and HttpModule in Real Scenario: Getting Started with HttpHandler
- HttpHandler and HttpModule in Real Scenario: Few examples of HttpHandler-1
In this article we will work with images in HttpHandler. Here we can get a few realy helpful information uses of HttpHandler.
Generate Dynamic Image within HttpHandler
In this example we will generate an image dynamically, within HttpHandler. This situation may occur when you want to generate a dynamic image at runtime. For example, when a Captcha image is generated. Have a look at the following code.
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.IO;
- using System.Linq;
- using System.Web;
- namespace WebApp
- {
- public class PictureHandler : IHttpHandler
- {
- public void ProcessRequest(HttpContext context)
- {
- int width = 200;
- int height = 200;
- Bitmap bitmap = new Bitmap(width, height);
- Graphics g = Graphics.FromImage((Image)bitmap);
- g.FillRectangle(Brushes.Red, 0f, 0f, bitmap.Width, bitmap.Height); // fill the entire bitmap with a red rectangle
- MemoryStream mem = new MemoryStream();
- bitmap.Save(mem, ImageFormat.Png);
- byte[] buffer = mem.ToArray();
- context.Response.ContentType = "image/png";
- context.Response.BinaryWrite(buffer);
- context.Response.Flush();
- }
- public bool IsReusable
- {
- get
- {
- return false;
- }
- }
- }
- }
If you have experience with the Drawing class in .NET then you can understand this example very quickly. Within the ProcessRequest() function we are generating an image with a specific height and width. Then we are setting this image within a memory stream and we are flashing it to an output stream.
Now, we need to register our custom PictureHandler in the web.config file. Here is the registration process.
- <system.webServer>
- <handlers>
- <add name="myImageHandler" verb="*" path="*.jpg" type="WebApp.PictureHandler"/>
- </handlers>
- </system.webServer>
Here is the output of above example.




Jeevan WijerathnaPosted Oct 13, 2016, 4:54 AM
How can we use this handler in src tag of image attribute in html?