title: HttpClientFactory TaskCanceledException: Unable to read data from the transport connection
body: <p>I have created a simple console app that downloads a single (PDF) file from archive.org using the <a href="https://github.com/aspnet/HttpClientFactory" rel="noreferrer">new ASP.NET Core 2.1 HttpClientFactory</a>. </p>
  
  <p>For the particular URL used in that program I always get a <code>TaskCanceledException</code>. If you try to run this code, you would probably get the same exception. It works for other URLs on archive.org though. When downloading the file using wget from the exact the same URL (<code>wget https://archive.org/download/1952-03_IF/1952-03_IF.pdf --output-document=IF.pdf</code>)
  the download is successful.</p>
  
  <p>However when I do it with <code>HttpClient</code> I get the below exception.</p>
  
  <p>What could I possible be doing wrong?</p>
  
  <p>Here is the simple code:</p>
  
  <pre><code>using System;
  using System.Net.Http;
  using System.Threading;
  using System.Threading.Tasks;
  using Microsoft.Extensions.DependencyInjection;
  using System.IO;
  using System.Diagnostics;
  
  namespace test2
  {
      public class Program
      {
          public static async Task Main(string[] args)
          {
              var serviceCollection = new ServiceCollection();
              serviceCollection.AddHttpClient("archive", c =&gt;
              {
                  c.BaseAddress = new Uri("https://archive.org/download/");
                  c.DefaultRequestHeaders.Add("Accept", "application/pdf");
              })
              .AddTypedClient&lt;ArchiveClient&gt;();
  
              var services = serviceCollection.BuildServiceProvider();
              var archive = services.GetRequiredService&lt;ArchiveClient&gt;();
              await archive.Get();
          }
  
          private class ArchiveClient
          {
              public ArchiveClient(HttpClient httpClient)
              {
                  HttpClient = httpClient;
              }
  
              public HttpClient HttpClient { get; }
  
              public async Task Get()
              {
                  var request = new HttpRequestMessage(HttpMethod.Get, "1952-03_IF/1952-03_IF.pdf");
                  var response = await HttpClient.SendAsync(request).ConfigureAwait(false);
                  response.EnsureSuccessStatusCode();
                  using (Stream contentStream = await response.Content.ReadAsStreamAsync(), 
                      fileStream = new FileStream("Worlds of IF 1952-03.pdf", FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
                  {
                      var totalRead = 0L;
                      var totalReads = 0L;
                      var buffer = new byte[8192];
                      var isMoreToRead = true;
  
                      do
                      {
                          var read = await contentStream.ReadAsync(buffer, 0, buffer.Length);
                          if (read == 0)
                          {
                              isMoreToRead = false;
                          }
                          else
                          {
                              await fileStream.WriteAsync(buffer, 0, read);
  
                              totalRead += read;
                              totalReads += 1;
  
                              if (totalReads % 2000 == 0)
                              {
                                  Console.WriteLine(string.Format("bytes downloaded: {0:n0}", totalRead));
                              }
                          }
                      }
                      while (isMoreToRead);
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>This is the full exception I get:</p>
  
  <pre><code>Unhandled Exception: System.Threading.Tasks.TaskCanceledException: The operation was canceled. 
  ---&gt; System.IO.IOException: Unable to read data from the transport connection: Operation canceled. 
  ---&gt; System.Net.Sockets.SocketException: Operation canceled    
  --- End of inner exception stack trace ---    
  at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error)    
  at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.GetResult(Int16 token)    
  at System.Net.Security.SslStreamInternal.&lt;FillBufferAsync&gt;g__InternalFillBufferAsync|38_0[TReadAdapter](TReadAdapter adap, ValueTask`1 task, Int32 min, Int32 initial)    
  at System.Net.Security.SslStreamInternal.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer)    
  at System.Net.Http.HttpConnection.FillAsync()    
  at System.Net.Http.HttpConnection.CopyToExactLengthAsync(Stream destination, UInt64 length, CancellationToken cancellationToken)    
  at System.Net.Http.HttpConnection.ContentLengthReadStream.CompleteCopyToAsync(Task copyTask, CancellationToken cancellationToken)    
  --- End of inner exception stack trace ---    
  at System.Net.Http.HttpConnection.ContentLengthReadStream.CompleteCopyToAsync(Task copyTask, CancellationToken cancellationToken)    
  at System.Net.Http.HttpConnection.HttpConnectionResponseContent.SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken) 
  at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)    at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)    
  at test2.Program.ArchiveClient.Get() in /Users/Foo/Temp/test3/Program.cs:line 42    
  at test2.Program.Main(String[] args) in /Users/Foo/Temp/test3/Program.cs:line 27    
  at test2.Program.&lt;Main&gt;(String[] args)
  </code></pre>