Skip to content

Commit a652233

Browse files
committed
Retry content header enumeration once on InvalidOperationException.
1 parent fe97f5f commit a652233

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

tools/Custom/HttpMessageLogFormatter.cs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,22 @@ internal static async Task<HttpRequestMessage> CloneAsync(this HttpRequestMessag
3838
await originalRequest.Content.CopyToAsync(ms);
3939
ms.Position = 0;
4040
newRequest.Content = new StreamContent(ms);
41-
originalRequest.Content.Headers?.ToList().ForEach(header => newRequest.Content.Headers.TryAddWithoutValidation(header.Key, header.Value));
41+
// Attempt to copy request content headers with a single retry.
42+
// In .NET Framework, HttpHeaders dictionary is not thread safe. See https://github.com/dotnet/runtime/issues/61798.
43+
int retryCount = 0;
44+
int maxRetryCount = 2;
45+
while (retryCount < maxRetryCount)
46+
{
47+
try
48+
{
49+
originalRequest.Content.Headers?.ToList().ForEach(header => newRequest.Content.Headers.TryAddWithoutValidation(header.Key, header.Value));
50+
retryCount = maxRetryCount;
51+
}
52+
catch (InvalidOperationException)
53+
{
54+
retryCount++;
55+
}
56+
}
4257
}
4358
return newRequest;
4459
}

0 commit comments

Comments
 (0)