Check GetStreamAsync status

淺唱寂寞╮ 提交于 2019-12-12 03:19:07

问题


Grabbing an image via GetStreamAsync, how do I determine status?

HttpClient OpenClient = new HttpClient();
Stream firstImageStream = OpenClient.GetStreamAsync("imageUrl.jpg").Result;

Sometimes this will give an error (403 or 404 typically) and I simply want to skip processing those results.

All I can find says to use the StatusCode property or IsSuccessStatusCode, but those seem to only work on HttpResponseMessage, which is from GetAsync, which does not give me the Stream I need to process the image.


回答1:


The stream doesn't have the response status code. You'll need to get the HttpResponseMessage first, check the status code, and then read in the stream.

HttpClient OpenClient = new HttpClient();
var response = await OpenClient.GetAsync("imageUrl.jpg");
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
    Stream stream = await response.Content.ReadAsStreamAsync();
}


来源:https://stackoverflow.com/questions/38724299/check-getstreamasync-status

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!