Displaying Images in ASP.NET Using HttpHandlers

Now you know what HttpHandlers are and how to setup them, we will write our own httpHandler to read the images from a database. Remember, this article explains creating httpHandler using the generic handler (.ashx). Since the .ashx file extension is already mapped in the IIS to the ASP.NET ISAPI filter, you do not have to configure your web.config file.

Create a new website in Visual Studio. Right-click on the project in the solution explorer and select Add New Item. From the available templates, add the new file of type Generic Handler and name it ImageHandler.ashx

Visual Studio opens a new file with the following content.

<%@ WebHandler Language="C#" Class="getImage" %>
 using System;
 using System.Web;
 
 public class getImage : IHttpHandler {
     
     public void ProcessRequest (HttpContext context) {
         context.Response.ContentType = "text/plain";
         context.Response.Write("Hello World");
     }
 
     public bool IsReusable {
         get  {
             return false;
         }
    }
 }

By default, the IHttpHandler is implemented. We will modify the code in ProcessRequest to read images from database. We are going to use the DataTable to read the data from the database.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace UserManagement
{
/// <summary>
/// Summary description for ImageHandler
/// </summary>
public class ImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
       string _imageId;
       if (context.Request.QueryString["id"] != null)
          _imageId = context.Request.QueryString["id"];
      else
      throw new ArgumentException("No parameter specified");


      SqlConnection objcon = new SqlConnection(System.Configuration.ConfigurationManager.
      ConnectionStrings["master"].ConnectionString);
      SqlCommand cmd = new SqlCommand();
      cmd.Connection = objcon;
      cmd.CommandText = "SELECT [Id],[Data] FROM [dbo].[ImageTable] where ID like '" + _imageId + "'";
      cmd.CommandType = System.Data.CommandType.Text;

      SqlDataAdapter da = new SqlDataAdapter(cmd);
      DataTable dt = new DataTable();
      da.Fill(dt);



      if (dt.Rows.Count > 0)
      {
         if (dt.Rows[0]["Data"] != DBNull.Value)
         {
             context.Response.ContentType = "image/jpeg";
             context.Response.BinaryWrite((byte[])dt.Rows[0]["Data"]);
         }
     }
   }
   public bool IsReusable
   {
      get { return false;}
   }
  }
}

now add image tage on Default.aspx page like.
<img alt=”test” src=”ImageHandler.ashx?id=9b27f3b5-9844-4ac9-8e60-7c6f1f0bb91f” />

Now run your application and the page (Default.aspx) displays the image served through HttpHandler.

Advertisements