在.net 8中使用HttpClientFactory时日志记录请求body和响应body
1、定义DelegatingHandler
public class LoggingHandler : DelegatingHandler { private readonly ILogger<LoggingHandler> _logger; public LoggingHandler(ILogger<LoggingHandler> logger) { _logger = logger; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // 记录请求信息 _logger.LogInformation("发送请求: {Method} {Uri}", request.Method, request.RequestUri); if (request.Content != null) { var requestBody = await request.Content.ReadAsStringAsync(); _logger.LogInformation("请求体: {RequestBody}", requestBody); } // 调用基类方法发送请求 var response = await base.SendAsync(request, cancellationToken); // 记录响应信息 _logger.LogInformation("接收到响应: {StatusCode}", response.StatusCode); if (response.Content != null) { var responseBody = await response.Content.ReadAsStringAsync(); _logger.LogInformation("响应体: {ResponseBody}", responseBody); } return response; } }
2、注入LoggingHandler 和配置使用LoggingHandler
var builder = WebApplication.CreateBuilder(args); //xxxxxxx builder.Services.AddTransient<LoggingHandler>(); builder.Services.AddHttpClient().ConfigureHttpClientDefaults(defaults=> defaults.AddHttpMessageHandler<LoggingHandler>());
然后通过注入IHttpClientFactory, 调用CreateClient方法创建HttpClient发起请求即可在日志中查看到请求的body和响应的body了