Introduction

This article explains tracing in the ASP. NET Web API. The use of tracing shows the diagnostic information of a single request of an ASP. NET page.

Working of Tracing

Features of Tracing

Tracing in Web API

In the ASP.NET Web API we can use our choice of tracing or logging library. In that we use the System.Diagnostics.Trace class.

Here is an example. There is a class that is implemented with the ITraceWriter interface.

  1. public class trace:ITraceWriter
  2. {
  3. public void Trace(HttpRequestMessage reqt, string type, TraceLevel step, Action<TraceRecord> traceAction)
  4. {
  5. TraceRecord record = new TraceRecord(reqt, type,step);
  6. traceAction(record);
  7. WriteTrace(record);
  8. }
  9. protected void WriteTrace(TraceRecord record)
  10. {
  11. var msg = string.Format("{0};{1};{2}",
  12. record.Operator, record.Operation, record.Message);
  13. System.Diagnostics.Trace.WriteLine(msg, record.type);
  14. }
  15. }

ITraceWriter Interface: There is a "Trace()" method for calling the trace action. It allows the setting of a value in the TraceRecord. Here we use the step, type,

traceAction and request that are the parameters of the ITraceWriter.

When we use the tracing in the Web API and for enabling the tracing in it, we need to implement our web API with the "ITraceWriter" Interface. Here we use the object

of the "HttpConfiguration" for doing this.

For example:

  1. public static void Register(HttpConfiguration config)
  2. {
  3. config.Services.Replace(typeof(ITraceWriter), new trace());
  4. }

For replacing the default traces we invoke "HttpConfigration.Services.Replace".

Add the Trace to the code

Add the trace to the code using this code:

  1. public class DetailsController : ApiController
  2. {
  3. public HttpResponseMessage GetAllDetails()
  4. {
  5. Configuration.Services.GetTraceWriter().Info(
  6. Request,"DetailsController","Get the all details of the Students");
  7. }
  8. }

Here we invoke the "HttpConfiguration.Services.GetTraceWriter" for getting the trace and it is accessed by the property of the "ApiController.Configuration".

Working of the Web AP Tracing