【发布时间】:2019-11-01 05:49:27
【问题描述】:
我调用一个互联网资源,当它返回“404 Not found”时,它会在响应流中发送更多信息。
第一个代码示例使用 VS 2017 中发现的新异步方法,如果对资源的调用失败并显示“404 Not found”,则会引发 AggregateException。 AggregateException 和其中包含的任何 InnerException 或 BaseException 似乎都不包含响应流:
1:
try
{
Uri reqUri = new Uri(query.ToString());
HttpRequestMessage webreq = new HttpRequestMessage(HttpMethod.Get, reqUri);
Task<byte[]> myTask = Task.Run(() => {return myClient.GetByteArrayAsync(webreq.RequestUri); });
}
catch(AggregateException aex)
{
HttpRequestException hrex = aex.InnerException;
// neither aex nor hrex contain a response stream
}
第二个代码示例使用 VS 2005 中已有的旧方法,如果对资源的调用失败并显示“404 Not found”,则会引发 WebException。 WebException 包含一个响应流:
2:
try
{
HttpWebResponse webResp;
HttpWebRequest httpReq;
httpReq = (HttpWebRequest)WebRequest.Create(query.ToString());
httpReq.Method = "GET";
webResp = (HttpWebResponse)httpReq.GetResponse();
}
catch(WebException wex)
{
Stream ReceiveStream = wex.Response.GetResponseStream();
}
是否可以修改代码示例 1,以便从 AggregateException aex 获取响应流?
【问题讨论】:
标签: c#