在 HttpClient 中记录请求/响应消息
使用 HttpClient 执行 POST 请求时,获取发布的实际 JSON 负载对于记录目的非常有价值。考虑使用自定义 LoggingHandler,而不是自己手动序列化对象。
通过在 HttpClientHandler 处理请求之前拦截请求,LoggingHandler 提供对请求和响应消息的访问。在 ReadAsStringAsync 方法中,ObjectContent 内的格式化程序会序列化对象,从而生成您要查找的 JSON 内容。
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; } }
集成 LoggingHandler HttpClient:
HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler())); HttpResponseMessage response = client.PostAsJsonAsync(url, "Hello, World!").Result;
输出日志:
Request: POST http://example.com/api/values Request Content: "Hello, World!" Response: 200 OK Response Content: "Hello, World!"
以上是如何在 C# 中使用 HttpClient 记录 HTTP 请求和响应消息?的详细内容。更多信息请关注PHP中文网其他相关文章!