Tuesday, 1 January 2013

.Net Tips : Get Image from Generic HTTP Handler file by implementing HttpHandler interface with C# Examples and VB.Net Examples

Click to Download C# Example ImplementHttpHandlersInCSharp.zip
Click to Download VB.NET Example ImplementHTTPHandlersInVBNET.zip

HttpHandlers is different from HttpModules. HttpHandlers positions in the request-processing pipeline is different from HttpModules. Using HttpHandlers we can map to a specific file extension.

Handlers are the final stop for incoming HTTP requests and the point in the request processing pipeline that is responsible for serving the requested content or data like. HTML , ASPX page, plain text, or an image.

Using HttpHandlers we can handle dynamic file download request.
HttpHandler using an ".ashx" file extension that allows to get started quickly and requires no server configuration.

You can add generic HttpHandler by simply select the Generic Handler file type from the Add New Item dialog in your project. Here below sample screen shot display. You may change the extension of file but this will require additional configuration in your deployment server. With ".ashx" extension you do not require any additional configuration.
When you add generic http handler in your application or project class stab is automatically added in ".ashx" file.

This class stub implements the IHttpHandler interface, which need you to implement the Process Request method and IsReusable property.

  • In ProcessRequest method you use to actually process the incoming HTTP request. By default, the class stub changes the content type to plain and then writes the “Hello World” string to the output stream.
  •  The IsReusable property lets ASP.NET know whether incoming HTTP requests can reuse the sample instance of this HttpHandler.

The handler generated automatically in you added file is ready to run right away. You can run this ".ashx" file in browser and see the result. This result depends on various factors like...
  • Browser type and version
  • Applications loaded on the system that may map to the MIME type
  • Operating system and service pack level

Based on these factors, you might see the text returned in the browser, you might see Notepad open and display the text, or you might receive the Open/Save/Cancel prompt from IE.

Here is example for this.
In this example we get images from "ImageHandler.ashx" file base on query string and display images directly in "<img>" tag. For that we added on "ImageHandler.ashx" file in our project and set content type "image/jpeg" in "ProcessRequest" method and depending on query string variable "id" value we can get image.

ASPX Code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>
            HTTP Handler class Impliment in Img tag
        </h1>
        <h1>Id : 1</h1>
        <img src="ImageHandler.ashx?id=1" alt="Dynamic Image" />

        <h1>Id : 2</h1>
        <img src="ImageHandler.ashx?id=2" alt="Dynamic Image" />

    </div>
    </form>
</body>
</html>

C# Examples (ImageHandler.ashx File) :

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

using System;
using System.Web;

public class ImageHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        context.Response.ContentType = "image/jpeg";
        if (context.Request.QueryString["id"] == "1")
        {
            context.Response.WriteFile("bamboo.jpg");
        }
        else
        {
            context.Response.WriteFile("palmtree.jpg");
        }
        
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

VB.Net Examples :
 
<%@ WebHandler Language="VB" Class="ImageHandler" %>

Imports System
Imports System.Web

Public Class ImageHandler : Implements IHttpHandler
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        'context.Response.ContentType = "text/plain"
        'context.Response.Write("Hello World")
        
        context.Response.ContentType = "image/jpeg"
        If context.Request.QueryString("id") = "1" Then
            context.Response.WriteFile("bamboo.jpg")
        Else
            context.Response.WriteFile("palmtree.jpg")
        End If
        
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

Output (Add new Generic Handler ".ashx" File): 

Add new Generic Handler ".ashx" File
(To view original image , click on image)


Output (Get Image from "ImageHandler.ashx" file) : 

Implement Generic HTTPHandler
(To view original image , click on image)


Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles according to that.



3 comments:

  1. Thank you so much it helped me so much !!! thank you!!!

    ReplyDelete