Home > Backend Development > C++ > How to Log HTTP Request/Response Messages Using HttpClient in C#?

How to Log HTTP Request/Response Messages Using HttpClient in C#?

Patricia Arquette
Release: 2024-12-31 15:14:10
Original
672 people have browsed it

How to Log HTTP Request/Response Messages Using HttpClient in C#?

Logging HTTP Request/Response Messages with HttpClient

When working with HttpClient, logging request and response messages is crucial for debugging and troubleshooting. This allows developers to inspect the actual data sent and received by the service.

One method for achieving this is by utilizing a custom LoggingHandler that intercepts both request and response messages. This handler can be chained with the underlying HttpClientHandler to observe the message flow.

Logging Handler:

public class LoggingHandler : DelegatingHandler
{
    public LoggingHandler(HttpMessageHandler innerHandler) : base(innerHandler)
    {
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Log request details
        Console.WriteLine($"Request:");
        Console.WriteLine(request.ToString());
        if (request.Content != null)
        {
            Console.WriteLine(await request.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        // Send request to inner handler
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

        // Log response details
        Console.WriteLine($"Response:");
        Console.WriteLine(response.ToString());
        if (response.Content != null)
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        return response;
    }
}
Copy after login

Usage:

To use the LoggingHandler, chain it with the HttpClientHandler as follows:

HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler()));
HttpResponseMessage response = client.PostAsJsonAsync(baseAddress + "/api/values", "Hello, World!").Result;
Copy after login

Output:

Executing the above code produces the following output:

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!"
Copy after login

By incorporating this logging mechanism, developers gain real-time insights into the HTTP requests and responses, allowing for efficient debugging and analysis of service interactions.

The above is the detailed content of How to Log HTTP Request/Response Messages Using 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