如何从url c#.Net Core获取图像

时间:2017-03-01 10:17:47

标签: c# asp.net-core

我使用HttpWebRequest从url获取流。在.Net Framework中,我得到这样的图像流:

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

这很完美。当我在.Net Core中执行此操作时,它确实有效。代码如下:

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

如何在ASP.NET核心中实现这一目标?

2 个答案:

答案 0 :(得分:0)

我想你得到AggregateException ProtocolViolationException。 (您可以在the other question on Stack Overflow找到详细说明。)

如果您尝试从远程网址获取内容,则应使用GetResponseAsync

顺便说一下,我建议在Asynchronous Programming上另外阅读。

答案 1 :(得分:0)

尝试一下:

 using (HttpClient c = new HttpClient())
 {
      using (Stream s = await c.GetStreamAsync(imgUrl))
      {
          // do any logic with the image stream, save it,...
      }
 }