services.AddHttpClient("MyClient") .AddHttpMessageHandler(); public class LoggingHandler : DelegatingHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Console.WriteLine($"{request.Method} {request.RequestUri}"); if (request.Content != null) { var requestBody = await request.Content.ReadAsStringAsync(); Console.WriteLine(requestBody); } var response = await base.SendAsync(request, cancellationToken); Console.WriteLine($"{(int)response.StatusCode} {response.StatusCode}"); if (response.Content != null) { var responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } return response; } }
services.AddHttpClient("MyClient") .AddHttpMessageHandlerThis code adds a named client "MyClient" and registers the AuthenticationHandler message handler to the client's pipeline. The handler is responsible for adding an Authorization header with a Bearer token obtained from an access token provider, before forwarding the request to the next handler in the pipeline. The package library used in this example may vary depending on the access token provider being used.(); public class AuthenticationHandler : DelegatingHandler { private readonly IAccessTokenProvider _accessTokenProvider; public AuthenticationHandler(IAccessTokenProvider accessTokenProvider) { _accessTokenProvider = accessTokenProvider; } protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var accessToken = await _accessTokenProvider.GetAccessTokenAsync(); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return await base.SendAsync(request, cancellationToken); } }