c# HttpRequestException: Error while copying content to a stream in HttpMessageHandler

707 views Asked by At

Using a custom RetryHandler in .NET for HttpClient.

//Create client
var client = new HttpClient(new RetryHandler(new HttpClientHandler()));

//PutAsync
var result = await client.PutAsync(new Uri($"{fileSystem}?resource=filesystem"), null).ConfigureAwait(true);

//Retry Handler
public class RetryHandler : DelegatingHandler
    {
        private const int MaxRetry = 3;
        private const int DelayMilliSeconds = 10000;

        public RetryHandler(HttpMessageHandler innerHandler)
            : base(innerHandler)
        {
        }

        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            HttpResponseMessage response = null;

            for (int i = 0; i < MaxRetry; i++)
            {
                try
                {

                    CancellationTokenSource source = new CancellationTokenSource(TimeSpan.FromMinutes(5));

                    response = await base.SendAsync(request, source.Token).ConfigureAwait(true);

                    if (response.IsSuccessStatusCode)
                    {
                        return response;
                    }
                }
                catch (Exception e)
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(Math.Pow(2, i) * DelayMilliSeconds));
                    continue;
                }
                Thread.Sleep(TimeSpan.FromMilliseconds(Math.Pow(2, i) * DelayMilliSeconds));
            }
            return response;
        }

Looks like that it never enters the RetryHandler, getting the following error before entering the RetryHandler.

System.Net.Http.HttpRequestException: Error while copying content to a stream. ---> System.ObjectDisposedException: Cannot access a closed Stream. at System.IO.Stream.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) at System.Net.Http.DelegatingStream.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) at System.Net.Http.StreamToStreamCopy.CopyAsync(Stream source, Stream destination, Int32 bufferSize, Boolean disposeSource, CancellationToken cancellationToken)

0

There are 0 answers