Search code examples
c#asp.netdebuggingasp.net-web-apitrace

HttpRequestMessage not set to an instance of an object


I have enabled tracing for my Web API application by creating a new ITraceWriter. It all works however I am not getting the request details from my TraceRecord as it throws an exception saying they are not set to an instance of an object.

public class LogTracer : ITraceWriter
{
    public void Trace(HttpRequestMessage request, string category, 
                TraceLevel level, Action<TraceRecord> traceAction)
    {
        TraceRecord traceRecord = new TraceRecord(request, category, level);
        traceAction(traceRecord);
        WriteTrace(traceRecord);
    }

    protected void WriteTrace(TraceRecord traceRecord)
    {
        var message = string.Format("\r\n\t{0} {1}\r\n\tOperator:{2}; 
        Operation: {3}; Message:{4}",
            traceRecord.Request.Method,
            traceRecord.Request.RequestUri,
            traceRecord.Operator,
            traceRecord.Operation,
            traceRecord.Message);

        System.Diagnostics.Trace.WriteLine(message, traceRecord.Category);
    }
}

Both traceRecord.Request throw a null reference exception. I have registered the tracer in my WebApiConfig as seen below:

config.Services.Replace(typeof(ITraceWriter), new LogTracer());

Solution

  • I fixed this by simply adding: request = new HttpRequestMessage(); Above my TraceRecord instantiation in the Trace method.