Logging Request/Response Messages in HttpClient
This article addresses the need for logging request and response messages when utilizing HttpClient. It focuses on the practical approach of logging the actual JSON content posted through HttpClient's PostAsJsonAsync method.
Solution:
To record the JSON content, we employ a DelegatingHandler named LoggingHandler. Interception takes place before the request reaches the HttpClientHandler, enabling access to the JSON data. ObjectContent's internal formatter produces the JSON representation captured by the LoggingHandler's ReadAsStringAsync method.
The implementation of the LoggingHandler class is as follows:
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; } }
This LoggingHandler must be chained with the HttpClient:
HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler())); HttpResponseMessage response = client.PostAsJsonAsync(baseAddress + "/api/values", "Hello, World!").Result;
The resulting output demonstrates the logging of both request and response messages, including the JSON content posted:
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!"
This technique provides a detailed logging mechanism for HttpClient requests and responses, aiding in debugging and monitoring communication over HTTP.
The above is the detailed content of How to Log Request and Response JSON Content Using HttpClient?. For more information, please follow other related articles on the PHP Chinese website!