How to write an ASHX file

If you develop with ASP.NET, you probably spend most of your time creating .aspx files with .cs files as code behind (or perhaps you use .ascx files for your controls -- and .asmx files for web services). But have you created a .ashx file (web handler). 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.

<% @ webhandler language="C#" class="AverageHandler" %>

using System;
using System.Web;

public class AverageHandler : IHttpHandler
{
   public bool IsReusable
   { get { return true; } }
   public void ProcessRequest(HttpContext ctx)
   {
       ctx.Response.Write("hello");
   }
}

You might also like...

Comments

Edward Tanguay Edward Tanguay updates his personal web site tanguay.info weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The greatest performance improvement of all is when a system goes from not-working to working.” - John Ousterhout