HttpRequestMessage未设置为对象的实例

时间:2018-10-25 14:39:47

标签: c# asp.net debugging asp.net-web-api tracing

我已经通过创建新的ITraceWriter为我的Web API应用程序启用了跟踪。一切正常,但是我没有从我的TraceRecord获取请求的详细信息,因为它抛出异常,表明未将它们设置为对象的实例。

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);
    }
}

两个traceRecord.Request都引发空引用异常。我已经在我的WebApiConfig中注册了跟踪器,如下所示:

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

1 个答案:

答案 0 :(得分:1)

我通过简单添加以下内容解决了此问题: request = new HttpRequestMessage();TraceRecord方法的Trace实例上方。