The .ashx extension – Writing your own HttpHandler

Have you noticed how Sitecore serves images using an .ashx extension? A .ashx file is a HttpHandler. A HttpHandler is kind of a lightweight aspx page, as the HttpHandler only deals with the HttpContext - for example there is no page information. This makes it a great tool for implementing providers for images, xml, rss feeds or other stuff that can be generated using parameters only.

The .ashx file implements the System.Web.IHttpHandler (or the System.Web.IHttpAcynchandler for async calls – I’ll only show the first one), which contains only 1 property (IsReusable) and one function (ProcessRequest()). The ProcessRequest() function have one parameter only, the HttpContext to read and write data to.

My Visual Studio have no default creation of .ashx extensions, so I’ll have to make one manually. I create a new file with the .ashx extension and adds the following line:

<% @ WebHandler language="C#" class="MyNamespace.MyClass" codebehind="mycodebehind.cs" %>

Then I have to create a mycodebehind.cs file and add a class called MyNamespace.MyClass. This class should implement the IHttpHandler interface:

using System.Web;

namespace MyNamespace
{
  public class MyClass : IHttpHandler
  {
    public bool IsReusable
    {
      get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
      // Here goes all of my code
    }
  }
}

Now my ProcessRequest can serve anything I like. I can reteieve paramaters from the Request and write to the Response:

public void ProcessRequest(HttpContext context)
{
  string parameter = context.Request.Params["myparameter"];
  context.Response.Write(parameter);
}

Or I can output a file (like Sitecore does):

public void ProcessRequest(HttpContext context)
{
  System.IO.MemoryStream ms = new System.IO.MemoryStream();
  Image image = SomeFunctionGeneratingAnImageForme();
  image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  context.Response.ContentType = "image/jpeg";
  context.Response.OutputStream.Write(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
}

I’ve noticed how Sitecore registers theit HttpHandlers in the web.config. You really don’t have to do that (even if Microsoft says so). You can call them directly. But if you wish to do so, you should read this article on how to register a HttpHandler.

One Response to “The .ashx extension – Writing your own HttpHandler”


Leave a Reply