-
Notifications
You must be signed in to change notification settings - Fork 1
Dotnet Core Intercept HTTP Requests
Jason Lewis edited this page Feb 7, 2024
·
2 revisions
- Add a LoggingHandler class (can be named anything you want)
public class LoggingHandler : DelegatingHandler { public LoggingHandler(HttpMessageHandler innerHandler) : base(innerHandler) { } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Console.WriteLine("Request:"); Console.WriteLine(request.ToString()); if (request.Content != null) { Console.WriteLine(await request.Content.ReadAsStringAsync()); } Console.WriteLine(); HttpResponseMessage response = await base.SendAsync(request, cancellationToken); Console.WriteLine("Response:"); Console.WriteLine(response.ToString()); if (response.Content != null) { Console.WriteLine(await response.Content.ReadAsStringAsync()); } Console.WriteLine(); return response; } }
- Add it as middleware to your HttpClient. E.g.
HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler())); var response = await _httpClient.SendAsync(request);