Logging Request/Response Messages in HttpClient
When performing POST requests with HttpClient, obtaining the actual JSON payload posted can be valuable for logging purposes. Instead of manually serializing the object yourself, consider utilizing a custom LoggingHandler.
By intercepting the request before it's handled by HttpClientHandler, LoggingHandler provides access to the request and response messages. In the ReadAsStringAsync method, the formatter inside the ObjectContent serializes the object, resulting in the JSON content you seek.
Example of a LoggingHandler:
public class LoggingHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(...) { Console.WriteLine($"Request: {request}"); Console.WriteLine($"Request Content: {await request.Content.ReadAsStringAsync()}"); HttpResponseMessage response = await base.SendAsync(...); Console.WriteLine($"Response: {response}"); Console.WriteLine($"Response Content: {await response.Content.ReadAsStringAsync()}"); return response; } }
Integrating the LoggingHandler with HttpClient:
HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler())); HttpResponseMessage response = client.PostAsJsonAsync(url, "Hello, World!").Result;
Output Log:
Request: POST http://example.com/api/values Request Content: "Hello, World!" Response: 200 OK Response Content: "Hello, World!"
The above is the detailed content of How Can I Log HTTP Request and Response Messages with HttpClient in C#?. For more information, please follow other related articles on the PHP Chinese website!