在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中文網其他相關文章!