HttpClient 사용시 요청 / 응답 메시지 로깅
다음과 같은 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을 직접 직렬화하지 않아도 좋을 것입니다.
이를 수행하는 방법의 예 :
몇 가지 참고 사항 :
LoggingHandler
HttpClientHandler
최종적으로 와이어에 쓰는 요청을 처리하기 전에 요청을 가로 챕니다 .PostAsJsonAsync
확장은 내부적으로를 생성하고 에서 호출ObjectContent
되면 내부 포맷터 가 객체를 직렬화하게하므로 json에서 콘텐츠를 보는 이유입니다.ReadAsStringAsync()
LoggingHandler
ObjectContent
로깅 핸들러 :
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;
}
}
위의 LoggingHandler를 HttpClient로 연결하십시오 .
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!"
See http://mikehadlow.blogspot.com/2012/07/tracing-systemnet-to-debug-http-clients.html
To configure a System.Net listener to output to both the console and a log file, add the following to your assembly configuration file:
<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>
Network tracing also available for next objects (see article on msdn)
- System.Net.Sockets Some public methods of the Socket, TcpListener, TcpClient, and Dns classes
- System.Net Some public methods of the HttpWebRequest, HttpWebResponse, FtpWebRequest, and FtpWebResponse classes, and SSL debug information (invalid certificates, missing issuers list, and client certificate errors.)
- System.Net.HttpListener Some public methods of the HttpListener, HttpListenerRequest, and HttpListenerResponse classes.
- System.Net.Cache Some private and internal methods in System.Net.Cache.
- System.Net.Http Some public methods of the HttpClient, DelegatingHandler, HttpClientHandler, HttpMessageHandler, MessageProcessingHandler, and WebRequestHandler classes.
- System.Net.WebSockets.WebSocket Some public methods of the ClientWebSocket and WebSocket classes.
Put next lines of code to the configuration file
<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>
The easiest solution would be to use Wireshark and trace the HTTP tcp flow.
참고URL : https://stackoverflow.com/questions/18924996/logging-request-response-messages-when-using-httpclient
'Programing' 카테고리의 다른 글
(마이너스) 스크롤바없이 화면 너비를 얻는 방법? (0) | 2020.08.30 |
---|---|
Razor 뷰 내부에서 ModelState.IsValid를 어떻게 확인할 수 있습니까? (0) | 2020.08.30 |
레일 3에 대한 유효성 검사 사용자 지정 메시지 (0) | 2020.08.30 |
중형 Clojure 샘플 애플리케이션? (0) | 2020.08.29 |
운영 체제와 커널의 차이점은 무엇입니까? (0) | 2020.08.29 |