0

I have a web service (web site) that returns a pdf as a binary file. You pass in an ID and get the contents of that particular pdf.

Say, for example: http://somesite.com/getPdf?id=12

This works fine.

I would like to call this from my .NET c# program.

I have tried the following, but I seem to be missing something:

   private static async Task GetPdf()
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/pdf"));
            client.DefaultRequestHeaders.Add("User-Agent", "someagent");
            var taskResponse= client.GetAsync("http://somesite.com/getPdf?id=12");

            var msg = await taskResponse;

        }

Am I approaching this correctly? Any suggestions would be greatly appreciated.

emaybert
  • 9
  • 3
  • What's the exact problem? – Timur Umerov Jun 20 '21 at 21:39
  • You're [leaving all your HTTP connections open forever](https://josefottosson.se/you-are-probably-still-using-httpclient-wrong-and-it-is-destabilizing-your-software/), is that what you think is wrong? – Dour High Arch Jun 20 '21 at 21:54
  • No, the above code throws an error when executing the await line, so I'm guessing I'm not invoking the Task correctly. This exception was originally thrown at this call stack: System.Web.ThreadContext.AssociateWithCurrentThread(bool) System.Web.HttpApplication.OnThreadEnterPrivate(bool) .... – emaybert Jun 20 '21 at 22:39
  • I've tried several variations of the code and I always get a "System.NullReferenceException: 'Object reference not set to an instance of an object.' error when executing the await line. I also cannot seem to gracefully catch the exception or check for a null response as VisualStudio itself throws the exception. – emaybert Jun 21 '21 at 11:13
  • The only thing I can think of is the remote url takes a bit of time to return the response. ( perhaps 10 seconds ). – emaybert Jun 21 '21 at 11:14
  • I suspect whatever is calling `GetPdf` is throwing the error. You need to [debug that](https://stackoverflow.com/questions/4660142/). – Dour High Arch Jun 21 '21 at 21:16
  • Thanks for the feedback. You're most likely correct as my call to GetPdf(); did not have the "await" keyword. When I tried to add it though, I got the error the the method that contained that call needed to be marked as async as well ( which makes sense ). Though the method is already marked as a [WebMethod] and it doesn't seem to allow you to mark a [WebMethod] as async. I will have to chase that down. – emaybert Jun 23 '21 at 01:31

0 Answers0