首页 >后端开发 >C++ >如何在 C# 中使用 HttpClient 记录 HTTP 请求/响应消息?

如何在 C# 中使用 HttpClient 记录 HTTP 请求/响应消息?

Patricia Arquette
Patricia Arquette原创
2024-12-31 15:14:10697浏览

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

使用 HttpClient 记录 HTTP 请求/响应消息

使用 HttpClient 时,记录请求和响应消息对于调试和故障排除至关重要。这允许开发人员检查服务发送和接收的实际数据。

实现此目的的一种方法是利用拦截请求和响应消息的自定义 LoggingHandler。此处理程序可以与底层 HttpClientHandler 链接以观察消息流。

日志处理程序:

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;
    }
}

用法:

要使用 LoggingHandler,请将其与 HttpClientHandler 链接为如下:

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

输出:

执行上述代码会产生以下输出:

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!"

通过合并此日志机制,开发人员实时洞察 HTTP 请求和响应,从而有效调试和分析服务交互。

以上是如何在 C# 中使用 HttpClient 记录 HTTP 请求/响应消息?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn