0

I'm using HttpWebRequest to get stream from url.In .Net Framework,I get image stream like this:

HttpWebRequest rq=(HttpWebRequest)WebRequest.Create(new Uri(url));
Stream stream=rq.GetRequestStream();

This works perfect.When I do this in .Net Core,it does't works.the code like this:

HttpWebRequest rq=WebRequest.CreateHttp(new Uri(url));
Stream stream=rq.GetRequestStreamAsync().Result;

How can I achieve this in ASP.NET core?

James Gould
  • 4,492
  • 2
  • 27
  • 50
John Wang
  • 33
  • 1
  • 2

2 Answers2

1

try this:

 using (HttpClient c = new HttpClient())
 {
      using (Stream s = await c.GetStreamAsync(imgUrl))
      {
          // do any logic with the image stream, save it,...
      }
 }
hojjat.mi
  • 1,414
  • 16
  • 22
-1

I suppose you are getting AggregateException of ProtocolViolationException. (You may find the detailed explanation at the other question on Stack Overflow.)

If you are trying to GET something from the remote URL, you should use GetResponseAsync.

By the way, I suggest additional reading on Asynchronous Programming.

Community
  • 1
  • 1
Dante May Code
  • 11,177
  • 9
  • 49
  • 81
  • User is trying to call an async method synchronously which is not needed/not a good practice but GetRequestStreamAsync().Result should also work, although it will be a blocking call. – SSA Mar 01 '17 at 10:56
  • @SSA Thanks. I did some field tests and updated the answer. – Dante May Code Mar 01 '17 at 11:07
  • 1
    @DanteisnotaGeek Thanks for your answer,I have tried to use GetResponseAsync stead of GetRequestStreamAsync,and it works well now. – John Wang Mar 02 '17 at 02:31