使用HttpClient时记录请求/响应消息

时间:2013-09-20 20:07:34

标签: c# .net asp.net-mvc-4 asp.net-web-api

我有一个方法可以执行如下所示的POST

var response = await client.PostAsJsonAsync(url, entity);

if (response.IsSuccessStatusCode)
{
        // read the response as strongly typed object
        return await response.Content.ReadAsAsync<T>();
}

我的问题是如何获取从实体对象发布的实际JSON。我想记录获得POSTED的JSON,所以如果没有我必须自己进行json序列化,那将是很好的。

4 个答案:

答案 0 :(得分:159)

如何执行此操作的示例:

一些注意事项:

  • LoggingHandler在将请求处理到最终写入电汇的HttpClientHandler之前拦截请求。

  • PostAsJsonAsync扩展程序在内部创建ObjectContent,在ReadAsStringAsync()中调用LoggingHandler时,会导致格式化程序 在ObjectContent内部来序列化对象,这就是你在json中看到内容的原因。

记录处理程序:

public class LoggingHandler : DelegatingHandler
{
    public LoggingHandler(HttpMessageHandler innerHandler)
        : base(innerHandler)
    {
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        Console.WriteLine("Request:");
        Console.WriteLine(request.ToString());
        if (request.Content != null)
        {
            Console.WriteLine(await request.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

        Console.WriteLine("Response:");
        Console.WriteLine(response.ToString());
        if (response.Content != null)
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        return response;
    }
}

使用HttpClient链接上述LoggingHandler

HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler()));
HttpResponseMessage response = client.PostAsJsonAsync(baseAddress + "/api/values", "Hello, World!").Result;

<强>输出:

Request:
Method: POST, RequestUri: 'http://kirandesktop:9095/api/values', Version: 1.1, Content: System.Net.Http.ObjectContent`1[
[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Headers:
{
  Content-Type: application/json; charset=utf-8
}
"Hello, World!"

Response:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Date: Fri, 20 Sep 2013 20:21:26 GMT
  Server: Microsoft-HTTPAPI/2.0
  Content-Length: 15
  Content-Type: application/json; charset=utf-8
}
"Hello, World!"

答案 1 :(得分:32)

请参阅http://mikehadlow.blogspot.com/2012/07/tracing-systemnet-to-debug-http-clients.html

要配置System.Net侦听器以输出到控制台和日志文件,请将以下内容添加到程序集配置文件中:

<system.diagnostics>
  <trace autoflush="true" />
  <sources>
    <source name="System.Net">
      <listeners>
        <add name="MyTraceFile"/>
        <add name="MyConsole"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add
      name="MyTraceFile"
      type="System.Diagnostics.TextWriterTraceListener"
      initializeData="System.Net.trace.log" />
    <add name="MyConsole" type="System.Diagnostics.ConsoleTraceListener" />
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose" />
  </switches>
</system.diagnostics>

答案 2 :(得分:7)

网络跟踪也可用于下一个对象(请参阅msdn上的文章)

  • 的System.Net.Sockets Socket,TcpListener,TcpClient和Dns类的一些公共方法
  • System.Net HttpWebRequest,HttpWebResponse,FtpWebRequest和FtpWebResponse类的一些公共方法,以及SSL调试信息(无效证书,缺少发行者列表和客户端证书错误。)
  • System.Net.HttpListener HttpListener,HttpListenerRequest和HttpListenerResponse类的一些公共方法。
  • System.Net.Cache System.Net.Cache中的一些私有和内部方法。
  • System.Net.Http HttpClient,DelegatingHandler,HttpClientHandler,HttpMessageHandler,MessageProcessingHandler和WebRequestHandler类的一些公共方法。
  • System.Net.WebSockets.WebSocket ClientWebSocket和WebSocket类的一些公共方法。

将下一行代码放入配置文件

<configuration>  
  <system.diagnostics>  
    <sources>  
      <source name="System.Net" tracemode="includehex" maxdatasize="1024">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Cache">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Http">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Sockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.WebSockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
    </sources>  
    <switches>  
      <add name="System.Net" value="Verbose"/>  
      <add name="System.Net.Cache" value="Verbose"/>  
      <add name="System.Net.Http" value="Verbose"/>  
      <add name="System.Net.Sockets" value="Verbose"/>  
      <add name="System.Net.WebSockets" value="Verbose"/>  
    </switches>  
    <sharedListeners>  
      <add name="System.Net"  
        type="System.Diagnostics.TextWriterTraceListener"  
        initializeData="network.log"  
      />  
    </sharedListeners>  
    <trace autoflush="true"/>  
  </system.diagnostics>  
</configuration>  

答案 3 :(得分:-8)

最简单的解决方案是使用Wireshark并跟踪HTTP tcp流。