What is an ASHX file Handler or web handler ?

Dec 31, 2009 Posted by Lara Kannan
In ASP.NET, you probably spend most of your time creating .aspx files with .cs files as code behind or use .ascx files for your controls and .asmx files for web services.

A web handler file works just like an aspx file except you are one step back away from the messy browser level where HTML and C# mix. One reason you would write an .ashx file instead of an .aspx file is that your output is not going to a browser but to an xml-consuming client of some kind.

Working with .ashx keeps you away from all the browser technology you don't need in this case. Notice that you have to include the IsReusable property.

What does the code there do?

It defines two parts of the IHttpHandler interface. The important part is ProcessRequest(), which will be invoked whenever the Handler.ashx file is requested or pointed to.

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

using System;
using System.Web;

public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}

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

Using query strings:

Developers commonly need to use the QueryString collection on the Request. You can use the Request.QueryString in the Handler just like you would on any ASPX web form page.

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

using System;
using System.Web;

public class QueryStringHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
HttpResponse r = context.Response;
r.ContentType = "image/png";
string file = context.Request.QueryString["file"];
if (file == "Arrow")
{
r.WriteFile("Arrow.gif");
}
else
{
r.WriteFile("Image.gif");
}
}

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

Now Debug the application:

When you pass Fille='Arrow' in query string like as follows

http://localhost:1372/FileHandler/QueryStringHandler.ashx?file=Arrow
You will get the output with arrow image. Otherwise you will get output as image.

http://localhost:1372/FileHandler/QueryStringHandler.ashx?file=Image

The above code receives requests and then returns a different file based on the QueryString collection value. It will return one of two images from the two query strings.

When we use Handler:

Here I want to propose some guidelines about when to use custom handlers and when to use ASPX web form pages. Handlers are better for binary data, and web forms are best for rapid development.

Use web forms (ASPX) when you have:

  • Simple HTML pages

  • ASP.NET custom controls

  • Simple dynamic pages

Use handlers (ASHX) when you have:

  • Binary files

  • Dynamic image views

  • Performance-critical web pages

  • XML files

  • Minimal web pages

Hope this will be useful.

Thanks : Purushottam

Share
Labels: ,

Post a Comment