Home > Backend Development > C++ > How Can I Log HTTP Request and Response Messages with HttpClient in C#?

How Can I Log HTTP Request and Response Messages with HttpClient in C#?

Linda Hamilton
Release: 2025-01-03 16:15:39
Original
988 people have browsed it

How Can I Log HTTP Request and Response Messages with HttpClient in C#?

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;
    }
}
Copy after login

Integrating the LoggingHandler with HttpClient:

HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler()));
HttpResponseMessage response = client.PostAsJsonAsync(url, "Hello, World!").Result;
Copy after login

Output Log:

Request: POST http://example.com/api/values
Request Content: "Hello, World!"
Response: 200 OK
Response Content: "Hello, World!"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template