Showing posts with label IHttpHandler. Show all posts
Showing posts with label IHttpHandler. Show all posts

Friday, 1 February 2013

Click to Download C# Example ImageMappedHandlerInCSharp.zip
Click to Download VB.NET Example ImageMappedHandlerInVBNET.zip


Http Handler using ".ashx" file extension and this is very convenient and understandable to all of us. But we can also custom this file extension with our requirement. To make customization in file extension we need to do add class file in "App_Code" folder and this class file implement "IHttpHandler" interface. And also mapping file extension in IIS and add settings in "web.config" file.

This configuration tell the application to show which file extension this handler serves. We can You do this by adding an <httpHandlers> section to the web.config file.
Here is configuration setting :
    <system.web>
      <httpHandlers>
        <add verb="*" path="ImageHandler.img" type="ImageMappedHandler, App_Code"/>
      </httpHandlers>
    </system.web>

This settings direct the application to use the "ImageMappedHandler" class to process incoming requests for ImageHandler.img. We can also specify wildcards for the path. By specifying *.img for the path which indicates that we want the application to use the ImageMappedHandler class to process any request with the
.img file extension. By specifying * indicates that we want all requests to the application to be processed using the handler.

Additional Configuration for IIS 7 :
If we run out web application on IIS 7 then we also must add the <handlers> configuration section to the <system.webServer> configuration section in our application’s config file. When adding the handler configuration in this section, we must also include the name attribute.

Configuration for IIS 7 :
  <system.webServer>
    <handlers>
      <add name="ImageHandler" verb="*" path="ImageHandler.img" type="ImageMappedHandler, App_Code" />
    </handlers>
  </system.webServer>

Now after doing this settings we can directly call ImageHandler.img from browser and we can get image from that.

Here is example for this.

Tuesday, 1 January 2013

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.