Debugging an HTTP Handler (*.ashx) in ASP.NET 2.0

By Dina Fleet Berry

A handler is responsible for fulfilling requests from a browser. Requests that a browser manages are either handled by file extension (or lack thereof) or by calling the handler directly. Only one handler can be called per request. A handler does not have any HTML static text like .aspx or .ascx files. A handler is a class that implements the IHttpHandler interface. If you need to interact with any Session information, you will also need to implement IRequiresSessionState. If you want to make an asynchronus handler, you will need to implement the IHttpAsyncHandler interface instead of the IHttpHandler interface.

Calling a Handler by File Extension

A handler can be invoked by any file extension that is mapped via the web.config and the IIS file extension mappings. You can have a file named something.billybob where 'billybob' is the file extension, or you can have no file extension at all such as http://web/handler/file where a request for 'file' without an extension invokes a handler mapped to *.* or the directory as *.

Calling a Handler Directory

The code file for the handler has the file extension of 'ashx' on the web server. This file can be called directly via a browser without having to set up web.config or IIS file extension mappings. For example: http://web/handler/handler.ashx. Some examples of this hander type are photo albums, RSS feeds, and blogging sites. Each of these is a good example of work that can be better accomplished without standard HTML. A photo album involves directory crawling and responding with pictures. A RSS feed returns information in the correct format.

Trace.axd as an Example Handler

An example of a handler that is invoked by file extension is the Trace.axd file used for debugging. In order to invoke the Trace.axd handler, you configure the website for tracing by adding a trace section to web.config:

<configuration>
    <system.web>
        <trace enabled="true"/>

    </system.web>
</configuration>

and call the trace.axd file from the root of the website such as http://localhost/trace.axd.

Required IIS Mappings for Handlers Called by File Extension

Handlers that are invoked based on a request's file extension require configuration in web.config and in the IIS file extension mapping. In order to see the file mapping of the *.axd file, open the IIS Manager and configure the application. Go to the 'Mappings' tab and scroll down until you see the .axd file extension.

Double-click on the .axd extension in order to see more details about this mapping.

Invoking handlers by file extension or no extension gives you flexibility about what is called and when. There are many articles on the web about file extension handlers so this article will focus on the handler that is called directly.

Creating a Handler

In order to create a handler code file, you need a web site in Visual Studio 2005 (or Visual Studio 2003 for a .NET 1.x handler). For a new website, select 'ASP.NET Web Site'.

This will create a web site with an App_Data directory and the default.aspx file. You won't use the default.aspx so you can either leave it alone or delete it.

You will need to create the web.config and the handler file by clicking on the website in the Solution Explorer and add new items of 'web.config' and 'Generic Handler'.

The handler code file will look like:

<%@ 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;
        }
    }

}

At this point, build the project and set the handler.ashx file as the startup file. Start debugging. You will be prompted to allow the process to change your web.config to allow debug. Unless you want to type in the change to allow debugging yourself ("<compilation debug="true"/>"), accept this change.

In my brower, because my desktop is set-up to parse text/plain as XML, I get an error that looks like:

The handler.ashx that Visual Studio provided needs to be fixed before it will work. So change the Content Type from 'text/plain' to 'text/html'. Build, and debug again. You should get a response that looks like:

Handler.ashx

The handler.ashx file implements the IHttpHandler interface and has two methods of 'ProcessRequest' and 'IsReusable'. The 'ProcessRequest' is your main method where you put your code. The 'IsReusable' method is set to true by default and indicates whether another request can use the IHttpHandler instance. If the instance can be reused mark it true -- this will improve the speed of the handler, and reduce the work your server will have to do. But if your instance should not be reused, due to state or because it is ansychronous, you should set IsReusable to false.

Session State

Before continuing, change the handler.ashx code to implement the IRequiresSessionState interface. If you need read-only access to the Session, implement the IReadOnlySessionState interface. Both interfaces are in the System.Web.SessionState namespace which you will need to add with the 'using' syntax. The code should now look like:

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

using System;
using System.Web;
using System.Web.SessionState;

public class Handler : IHttpHandler , IReadOnlySessionState{

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/html";
        context.Response.Write("Hello World");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

Set a break point for the first line in the class and start debugging again.

Handling Issues with a Debug Build

When you use a debug build, you have the full resources of the Visual Studio debugger, all .NET Framework namespaces, and any system utilities and applications. The Visual Studio Debugger allows you to view the call stack, local variables, any watch variables, etc. You are probably familiar with using these features to some degree. However, with a HTTP Hander, debugging is much more important because the only visual indication of a bug is whatever you code into the content.

Handling Issues with a Release Build

The release build is different from the debug build in both features and performance. When you are using a release build, it is probably in a production environment. As such, you will need to use a different set of tools to find your issues.

Debugging with System.Diagnostics Namespace

The Diagnostics namespace has many classes to help with debugging in release and debug mode. If you are debugging in release mode, you should use the Trace class. If you are debugging in debug mode, you should use the Assert class. This article doesn't cover all the abilities of this namespace so you should investigate what class will help you solve your immediate problem.

In order to show these classes in action, change the code to use the namespace and use an infinite loop. The assertion is throw when the expression in the assertion is false, so the assertion will throw when the counter is no longer less than 10.

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

using System;
using System.Web;
using System.Web.SessionState;
using System.Diagnostics;

public class Handler : IHttpHandler , IReadOnlySessionState{

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/html";
        context.Response.Write("Hello World");

        int i=0;

        while (1!=0)
        {
            Debug.Assert(i<10);
            i++;
        }

    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

Build and debug. Since there are no breakpoints set, the debugger will become active again when the assertion is hit. This is great if you know what the error is you are getting and can test for it. The first thing that happens is an assertion window pops up with information about the assertion. If you want the debugger to become active, click the "Retry" button. This will bring up the debugger at that assertion code line.

If you know a general code location you would like to look at instead of a specific Boolean statement to test for, you should use the Debugger.Break statement in your code. This will pop up the debugger as well. If you want to look at preconditions and then stop at the error, you can combine these two statements to quicken your debugging process. An example of that code is below:

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

using System;
using System.Web;
using System.Web.SessionState;
using System.Diagnostics;

public class Handler : IHttpHandler , IReadOnlySessionState{

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/html";
        context.Response.Write("Hello World");

        Debugger.Break();

        int i=0;

        while (1!=0)
        {
            Debug.Assert(i<10);
            i++;
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

You can use the Debug.Write, Debug.WriteIf, Debug.WriteLine, and Debug.WriteLineIf to print to the Output window during a debug session. This could help you view the state of the HTTP Handler.

If you want to track down an issue in a release build, you will have to have a way of peering into the code. One way to do that is to add EventLog.WriteEntry statements into your code. This allows you to add information to the event log as the HTTP Hander is running. The WriteEntry method is heavily overloaded so you will need to determine the best method for your use. If you want to see information as a simple information entry in the event viewer, you just use one String argument. The Event Viewer needs to know the "Source" of the event so let's name it "HTTPHandler - DebugArticle". This should be easy to see in the Event Viewer. The code looks like:

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

using System;
using System.Web;
using System.Web.SessionState;
using System.Diagnostics;

public class Handler : IHttpHandler , IReadOnlySessionState{

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/html";
        context.Response.Write("Hello World");

        int i=0;

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "HTTPHandler-DebugArticle";

        while (i<100)
        {
            if (i/10==0)
            {
                // Write an informational entry to the event log.
                myLog.WriteEntry("Writing to event log: i is divisible by 10.");
            }
            i++;
        }

    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

Build a release version of the handler and call it. The output should only include the "Hello World" text. Open the Event Viewer, Application log. You should see several postings from the source of "HTTP Handler - DebugArticle".

If you open one of the events, you should see a simple output:

There are also classes to interact with the Performance monitor, and processes as well as several classes to help with logic flow.

Attaching to a Process to Debug a Running HTTP Handler

Another method of finding your issues is to attach to a process that contains the HTTP Handler. If you are running multiple websites where each website is in it's own process space, you may have to figure out the process id. The easiest way is to have your handler tell you. The System.Diagnostics namespace includes a class called Process which will help you determine the current process's id. In order to find the id, let's send the id to the event viewer by changing the code to:

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

using System;
using System.Web;
using System.Web.SessionState;
using System.Diagnostics;

public class Handler : IHttpHandler , IReadOnlySessionState{

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/html";
        context.Response.Write("Hello World");

        int i=0;

        Process.GetCurrentProcess().Id.ToString();

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "HTTPHandler-DebugArticle";
        myLog.WriteEntry("Process Id is " + Process.GetCurrentProcess().Id.ToString());

        while (i<100)
        {
            if (i/10==0)
            {
                // Write an informational entry to the event log.
                myLog.WriteEntry("Writing to event log: i is divisible by 10.");
            }
            i++;
        }

    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

The important code line here is in the loop and is an alteration to the string in the myLog.WriteEntry:Process.GetCurrentProcess().Id. The following figure shows what the Event Viewer entry looks like:

Now that you know the process id, you need to find this id in the Task Manager. In order to see process ids in the Task Manager, click to the Process tab then click on View and choose Select Columns. Click on PID (Process Identifier) and OK out of the Dialogs. The list of processes should now include the PID, which you can sort by if you click on the column name. Once you find the right process id in the list, right click on it and choose Debug. This will start Visual Studio. You will have to open your code file from Visual Studio and debug at that point.

Summary

An ASP.NET HTTP Handler is a simple class that allows you to process a request and return a response to the browser. The handler gives you access to the current web context and the session state. The default 'Generic Hander' that Visual Studio 2005 gives you may not work with its current code. With a few changes, working with the System.Diagnostics namespace will have you writing HTTP handlers that build and debug successfully.



Comments

  • What is so virtuous about headphones

    Posted by motherdhmm on 06/04/2013 09:07pm

    [url=http://www.headphonescheaponlineaustralia.com/]beats headphones Australia[/url] We call to mind a consider you on destitution okay headphone or earphone to attend to music and get wind of some dependable sounds.Enjoy fast-moving games and your darling music wherever you go.Provide various stiff eminence earphone, Headphone products to all customers.We improvise you pass on like these feelings that take advantage of our headphone or earphone to pay attention to to music.We New Sort Beats resolution put up for sale you concern and pre-eminent service. [url=http://www.headphonescheaponlineaustralia.com/]beats by dre[/url] The music, we horridness beats know this unique knowledge instead of thousands of years seems to include unbreakable hold together with humans; it brings more technique on the astound Qiexi, carnival.Whether old or inexperienced, we monster beats dr.dre differentiate there is in every human being¡¯s heart the catch of wonders, the unfailing childlike zeal of what are next and the bliss of the match of living.Whether getting on in years or children, we monster beats dr.dre recognize there is in every soul being¡¯s spunk the coax of wonders, the unfailing childlike appetite of what are next and the ecstasy of the meeting of living. [url=http://www.headphonescheaponlineaustralia.com/]monster beats Australia[/url] Beats close Dre Studio are precision-engineered to divulge the full quality of today¡¯s digital music including the most sonically demanding tor, cool spring and R&B. With advanced rabble-rouser lay out, powered amplification, and bustling bruit about canceling, Beats by Dre Australia delivers all the power, pellucidity, and deep bass today¡¯s cover artists and producers want you to hear. This Horror Beats can bring on you the recent adventure, snag it, don¡¯t welcome it twig away from your hands.

    Reply
  • Surprise etter monster beats kommer alltid pÃ¥ moten

    Posted by mantouhmmm on 06/04/2013 02:30pm

    [url=http://www.drebeatsnorge.qsite.dk/]beats by dre norge[/url] Lav overflod er fortsatt Studio fokus - forutsatt tiltalende akseptabelt i lav frekvens. Ikke som Tour, er Flat lav overflod tykkere og enklere, ingen overdriver bottomward men bare affære behovene til musikk som Hip-Hop. Topp overflod er en av de aspektene som vi aksepterer kritisert on Tour - det er for aciculate og ikke omgjengelige i det hele tatt. Mens Flat betaler ekstra absorpsjon til antitese og lav overflod - litt "overkompensasjon" på toppen frekvens, motvektstrucker og litt defekt av detaljer. Derfor er som en dyktig Flat artikulasjon sentrert i gjennomsnittlig overflod og lav overflod som ikke er faktisk akseptabelt for som liker flammer akutt stemme. På slutten av artikkelen, anerkjennelse jeg hotsalesmart.com til deg, Monster beats by dr. dre flat alene er $ 169 til $ 219 for chargeless forsendelsen hjem. [url=http://www.monsternobeats.350.com/]monster beats[/url] Uansett hva din stil av musikk tutorials gjør det mulig for alle som er seriøse om å lære å skape sin egen stil av music.This musikk lage programvare er veldig lærerikt, og er en kraftig beat maker for å produsere beats. Det spiller ingen rolle om du bare starte opp, eller hvis du er en erfaren musician.With den vennlige brukergrensesnittet kan du velge ulike trommesett, og deretter redigere volumer av hver, og hver blokk. Deretter kan du redigere lyd, og spille pads med triggere. Dub Turbo har noen fantastiske trommesett med effekter, slams, hits og mer. Alt dette høres uvant, overveldende, og kan gjøre deg engstelig. Veiledningene dekker alt dette, og vil hjelpe deg å forstå musikken terms.By følge tutorials en nybegynner bør være i stand til å ha sine første låter satt sammen i løpet av en time. [url=http://www.monsternobeats.350.com/]monster beats[/url] Once du har lastet ned flere beats, og du er fornøyd med beats som du har lastet ned. Da er det tid kompilere og polere opp på beats når beats er godt arrangert, og lyden er god, og du har spilt den om og om igjen, og du er fornøyd med det endelige produktet så er du god til å go.Once dine beats er klar så er det på tide å dele dine sluttprodukter med venner og familie. Det er også anledning til å lansere deg som en rap artist gjennom å tilby gratis rap beats og selge rap musikk på nettet. Dette gjelder også andre sjangere av musikk som du oppretter gjennom gratis online beats nedlasting.

    Reply
  • gque sea posible puede disfrutar de ritmos por el dr. dre

    Posted by cheneason on 06/04/2013 11:27am

    [url=http://www.cascos-beats-baratos.webnode.fr/]beats by dr dre[/url] Producenter frembringer deres egne beats på nettet åbner ubegrænsede samarbejdsmuligheder med hensyn til designere på et stramt budget. Den særlige udseende tilgængelig er utallige der en bred vifte af friske rekorder på markedet hver dag derude sted. I tilfælde af at du synes at købe overgår, anmeld af din web selskabet samt høre deres varer. Du er i stand til at Google eller måske Ask tilstande såsom “internet-producenter” eller “køb er bedre end online” og masser af troværdige producent internetsider vil helt sikkert producere.En anden tendens jeg opdager i trap rekorder kunne være den store brug af rumklang omkring den primære enhed. Der er typisk en enkelt pind ud værktøj put, der har en velvoksen reverb effekt sige for eksempel en grand violin, guitar, samt synth. I de fleste tilfælde en let melodi, der gentager flere gange samt modulerer op eller ned. Processen mod kaos er meget simpelt, så prøv ikke at under vurdere de grunde, der kan placeres i dette. beats [url=http://www.auricularesbeats.weebly.com/]auriculares beats[/url] Beats By Dr. Dre Beats Wireless har annonceret et trådløst Bluetooth-headset. Dette er udformningen af den populære Solo HD og kan let kobles med en smartphone eller tablet. Den nye model er også udstyret med ControlTalk, med en mikrofon i øret og alle nødvendige kontroller. Beats By Dr. Dre introducerer Beats trådløse Bluetooth hovedtelefoner Beats By Dr. Dre Beats introducerer den trådløse Bluetooth-hovedtelefoner lytteren fuld musikalsk frihed. [url=http://www.auricularesbeats.weebly.com/]beats by dre españa[/url] Mange musikelskere tror, Musik er noget, der flyder gennem nerverne, som er bogstaveligt talt sandt, trods alt, føler det samme, da de mener. Så hvis du er til musik på en seriøs måde, så hvordan du foretrækker at flyde igennem det? Nå, jeg tror den bedste lydkvalitet ville være dit første præferencer for at øge smagen af din yndlingsmusik. Nå, mange tror musik er den del af livet, så mener jeg det samme. Det er noget, svært at forklare, men det eneste, du kan gøre med det, er føler. Derfor, dette er hvad alt hvad du behøver, det fedeste og kvalitet dr. dre Horetelefoner til at føle det bedre.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • Due to internal controls and regulations, the amount of long term archival data is increasing every year. Since magnetic tape does not need to be periodically operated or connected to a power source, there will be no data loss because of performance degradation due to the drive actuator. Read this white paper to learn about a series of tests that determined magnetic tape is a reliable long-term storage solution for up to 30 years.

Most Popular Programming Stories

More for Developers

RSS Feeds