Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 32 additions & 18 deletions tools/Custom/HttpMessageLogFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,27 +34,34 @@ internal static async Task<HttpRequestMessage> CloneAsync(this HttpRequestMessag
// Set Content if previous requestClone had one.
if (originalRequest.Content != null)
{
// HttpClient doesn't rewind streams and we have to explicitly do so.
var ms = new MemoryStream();
await originalRequest.Content.CopyToAsync(ms);
ms.Position = 0;
newRequest.Content = new StreamContent(ms);
// Attempt to copy request content headers with a single retry.
// HttpHeaders dictionary is not thread-safe when targeting anything below .NET 7. For more information, see https://github.com/dotnet/runtime/issues/61798.
int retryCount = 0;
int maxRetryCount = 2;
while (retryCount < maxRetryCount)
// Try cloning request content; otherwise, skip due to https://github.com/dotnet/corefx/pull/19082 in .NET 4.x.
try
{
try
// HttpClient doesn't rewind streams and we have to explicitly do so.
var ms = new MemoryStream();
await originalRequest.Content.CopyToAsync(ms).ConfigureAwait(false);
ms.Position = 0;
newRequest.Content = new StreamContent(ms);
// Attempt to copy request content headers with a single retry.
// HttpHeaders dictionary is not thread-safe when targeting anything below .NET 7. For more information, see https://github.com/dotnet/runtime/issues/61798.
int retryCount = 0;
int maxRetryCount = 2;
while (retryCount < maxRetryCount)
{
originalRequest.Content.Headers?.ToList().ForEach(header => newRequest.Content.Headers.TryAddWithoutValidation(header.Key, header.Value));
retryCount = maxRetryCount;
}
catch (InvalidOperationException)
{
retryCount++;
try
{
originalRequest.Content?.Headers?.ToList().ForEach(header => newRequest.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value));
retryCount = maxRetryCount;
}
catch (InvalidOperationException)
{
retryCount++;
}
}
}
catch
{
}
}
return newRequest;
}
Expand All @@ -66,7 +73,14 @@ public static async Task<string> GetHttpRequestLogAsync(HttpRequestMessage reque
string body = string.Empty;
try
{
body = (requestClone.Content == null) ? string.Empty : FormatString(await requestClone.Content.ReadAsStringAsync());
if (requestClone.Content != null)
{
body = FormatString(await requestClone.Content.ReadAsStringAsync());
}
else if (requestClone.Content == null && request.Content != null)
{
body = "Skipped: Content body was disposed before the logger could access it.";
}
}
catch { }

Expand Down