Logging HTTP Request and Response Messages using HttpClient
In situations where you need to capture the request and response messages during HTTP communication using HttpClient, logging becomes essential. Consider the following code snippet:
var response = await client.PostAsJsonAsync(url, entity); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsAsync<T>(); }
Now, let's explore how to obtain the JSON payload sent within the 'entity' object without manually serializing it.
Solution: Custom Logging Handler
To intercept and log request and response messages, you can create a custom logging handler that wraps around the HttpClientHandler. This handler will intercept requests before HttpClientHandler processes them. An example implementation could be:
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; } }
In this handler:
Chaining the Logging Handler with HttpClient
To use the logging handler, you need to chain it to your HttpClient:
HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler())); HttpResponseMessage response = client.PostAsJsonAsync(baseAddress + "/api/values", "Hello, World!").Result;
Example Output
The output of the above code would look like this:
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!"
By utilizing this approach, you can effectively log the request and response JSON messages during HTTP calls made with HttpClient, providing valuable insights for debugging and troubleshooting purposes.
The above is the detailed content of How to Log HTTP Request and Response JSON Messages using HttpClient?. For more information, please follow other related articles on the PHP Chinese website!