Sunday, May 03, 2009

Adding trace to ASHX files

This is almost certainly caused by me being an idiot, but I know there are other people out there who are idiots on occasion so I thought I’d post this. I’ve never used Trace.Write in ASP.NET before and the first place I needed to use it was in a generic handler ASHX page. I didn’t look too closely at what was required and assumed that I needed to use Trace.Write in System.Diagnostics. That was my first mistake. This doesn’t add any trace output to the trace.axd page (though it would be cool if it did since I could then add trace to my assemblies that would show up, perhaps adding a custom trace listener could fix this?).

So then I looked at the code for System.Web.UI.Page and realised it has a Trace property but a generic handler doesn’t have this property so I thought that I might be out of luck. Eventually I realised that the HttpContext passed into the ProcessRequest method has a Trace property so I could just use that for all my tracing needs. Problem solved.

Update: I’ve now realised it’s pretty easy to include trace output from System.Diagnostics.Trace calls in ASP.NET apps. Just add the following to web.config

    <trace autoflush="false" indentsize="4">
        <add name="WebPageTraceListener"
            type="System.Web.WebPageTraceListener, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

No comments: