0

I have HttpClient code which is supposed to download a PDF/Word document from given URL (SSRS report) and convert it to a memory stream but that is not working for all cases.

Sample URL:

http://server/ReportServer_SQL1?/Team/Report&rs:Command=Render&user=employeename&Liability=Current&Role1=MGA&rs:Command=Render&rc:Parameters=Collapsed&rs:Format=image

Error:

System.Net.WebException: An exception occurred during a WebClient request. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) --- End of inner exception stack trace --- at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.WebClient.DownloadBitsState.RetrieveBytes(Int32& bytesRetrieved) at System.Net.WebClient.DownloadBits(WebRequest request, Stream writeStream, CompletionDelegate completionDelegate, AsyncOperation asyncOp) at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) --- End of inner exception stack trace --- at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) at System.Net.WebClient.DownloadData(Uri address)

Code

using (HttpClient client = new HttpClient())
{
    client.Timeout = Timeout.InfiniteTimeSpan;
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Add("Authorization", "Basic " + encPassword);
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;

    // Error happens on this line
    var result = client.GetAsync(url).GetAwaiter().GetResult(); 

    if (result.IsSuccessStatusCode)
    {
        var responseContent = result.Content;
        var result_data = responseContent.ReadAsStreamAsync().GetAwaiter().GetResult();
        ms = (MemoryStream)result_data;
    }
    else
    {
        throw new Exception("Authentication issue");
    }
}
Amir
  • 69
  • 1
  • 12
  • 2
    could you provide full error? with stack traces (if not sensitive) – Manish May 23 '23 at 12:05
  • 3
    Why are you so desparate to not use `async`? Side note: `ServicePointManager.SecurityProtocol...` why do you have this? Just rely on the operating system to do the TLS protocol. Also `ms = (MemoryStream)result_data;` you can't do this as it might not be a `MemoryStream`, equally I don't why you would ever need to do so. – Charlieface May 23 '23 at 12:08
  • Why don't you make this method `async`? Downloading a file should be an asynchronous operation in general. – Mustafa Özçetin May 23 '23 at 12:14
  • Also note that the recommended way is to create `HttpClient` objects using the `IHttpClientFactory` interface. Please have a look at [this post](https://stackoverflow.com/questions/75953233/c-sharp-httpclient-and-api/75953415#75953415). – Mustafa Özçetin May 23 '23 at 12:18
  • @Charlieface This is a legacy code developed in .NET 4.5 framework. This code is just a part of a big functionality which is accessed in all over the legacy application. If I where to change the code to async the amount of changes I need to do the reference code will increase and regression test the whole application. – Amir May 23 '23 at 12:46
  • 1
    Did you refactor to `HttpClient` from something else? If so: why? – Fildor May 23 '23 at 13:39
  • @Fildor I refactored the code to HttpClient from WebClient because I need to pass on Authorization token in request header. – Amir May 23 '23 at 15:58
  • So what is the full error message, and why do you need a `memoryStream` as opposed to just a `Stream`? – Charlieface May 23 '23 at 15:59
  • The error happens at this line var result = client.GetAsync(url).GetAwaiter().GetResult(); Error - Error while copying content to a stream. I am working on to get the full error. – Amir May 23 '23 at 16:01
  • 1
    https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.headers?view=netframework-4.5 .Net Framework 4.5 WebClient supports Headers? – Fildor May 23 '23 at 16:01
  • @Fildor I tried the same earlier and it was not working that is why I move towards HttpClient. This above code in the question is working 50-50. The failure case may be because of size the file it tries to download. – Amir May 23 '23 at 16:06

0 Answers0