Friday, March 01, 2013

How To Create a simple .Net HttpHandler

I'm writing a heartbeat diagnostic page that will test all the database connections and make sure my application is up and running.   Since it produces a page that will be read by a monitor very frequently I chose to make it an  HttpHandler.  Normal .aspx pages go through like
12 events or so.  Since I don't need the full power, and resource consumption, of an aspx page, an HTTPHandler seemed like a good idea.
It's actually quite easy to create an HTTPHandler in .Net.  This shows how to integrate a single HTTPHandler into an existing .Net 4.5 project using VS2012.

The first step is to create a .cs class which implements IHttpHandler, mine is named Heartbeat.cs:

using System;
using System.Web;

namespace MyNamespace
    public class Heartbeat : IHttpHandler
        public bool IsReusable
            get { return true; }
        public void ProcessRequest(HttpContext context)
           context.Response.Write("Hi There!");

The second step is to create a .ashx page with one line.  Here's my Heartbeat.ashx page:

<% @ WebHandler language="C#" class="SurveyDirector.Heartbeat" codebehind="Heartbeat.cs" %>
And you are done.
Now entering the URL

I get

Hi There!