Trace.Write not working in my ASP.NET handler – How to trace your generic .ashx handler

Today I needed to trace my small ASP.NET application which consists of one .ashx file that will handle requests. Because this handler will respond with text I need to write my trace somewhere else than to the bottom of the page (which is possible in .aspx page). I also can’t write Trace=”true” in .ashx file. So how to make your trace work?

  • Open web.config file and add
    <trace enabled="true" />

    in

    <system.web>

    node,

  • Also add
    <system.diagnostics>
     <trace autoflush="true" indentsize="4">
     <listeners>
     <add name="webListeners"
     type="System.Web.WebPageTraceListener, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
     </listeners>
     </trace>
     </system.diagnostics>

    in <configuration> node. (I found out that although I call Trace.Write in my code, nothing is written anywhere),

  • Call Trace.Write or some other method in you code.

When you execute request against you handler (Trace.Write gets executed) and then go to yourapp/trace.axd you will be able to see all requests and clicking on you your_handler_name.ashx’s file View Details link you will be able to see something like this :

trace from asp dot net handler

Without adding webListener entry to web.config you wouldn’t be able to see any of your Trace.Write messages. In normal .aspx file this works out of box. You just enable it in web.config file and use Trace.Write and that’s all. Pages derives from System.Web.UI.Page but handlers from IHttpHandler, so this is the difference.

Here is whole sample app packaged, if you need it (look for TraceHandlerWebApplication.zip file) :

https://skydrive.live.com/redir.aspx?cid=78a5783de37d2ebe&resid=78A5783DE37D2EBE!1782&parid=root

Enjoy.

One thought on “Trace.Write not working in my ASP.NET handler – How to trace your generic .ashx handler

Leave a Reply

Your email address will not be published. Required fields are marked *