最近在项目中发现,HttpClient中调用某Api总是出现403的异常,自己使用postman 调用即没有问题,经排查是HttpClient 会自动添加traceparent请求头
Accept-Encoding: gzip User-Agent: Firefox/5.0 (Linux 3.4; rv:14.0) Gecko/20100101 Firefox/91.0 traceparent: 00-274628f3ce14109d06680c90e8cc19ca-42e0b82e7d106403-00 Content-Type: application/x-www-form-urlencoded Content-Length: 160
原因是:在HttpClient 调用SendAsync 时,如果Activity的IdFormat 等于ActivityIdFormat.W3C 就会添加traceparent参数
代码来源:https://github.com/dotnet/runtime/blob/release/5.0/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs#L286
private static void InjectHeaders(Activity currentActivity, HttpRequestMessage request) { if (currentActivity.IdFormat == ActivityIdFormat.W3C) { if (!request.Headers.Contains(DiagnosticsHandlerLoggingStrings.TraceParentHeaderName)) { request.Headers.TryAddWithoutValidation(DiagnosticsHandlerLoggingStrings.TraceParentHeaderName, currentActivity.Id); if (currentActivity.TraceStateString != null) { request.Headers.TryAddWithoutValidation(DiagnosticsHandlerLoggingStrings.TraceStateHeaderName, currentActivity.TraceStateString); } } } ..... }
所以这里把Activity.Current=null即可
Activity.Current = null; var response = await _httpClient.PostAsync("your url", content);
参考文献:c# - Remove TraceParent header from HttpClient requests - Stack Overflow
标签:currentActivity,request,Headers,添加,Activity,traceparent,HttpClient From: https://www.cnblogs.com/mtyh/p/18146245