使用 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,請將其與 HttpCldler連結為如下:
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中文網其他相關文章!