[英]How to obtain a web response exception stream when returned exception is “AggregateException” instead of “WebException”
我調用一個互聯網資源,當它返回“404 Not found”時,它會在響應 stream 中發送更多信息。
第一個代碼示例使用 VS 2017 中發現的新異步方法,如果對資源的調用失敗並顯示“404 Not found”,則會引發 AggregateException。 AggregateException 和其中包含的任何 InnerException 或 BaseException 似乎都不包含響應 stream:
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 包含響應 stream:
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?
看來我找到了解決上述問題的方法。 我將示例 1 修改為:
HttpClient myClient = new HttpClient;
Task<HttpResponseMessage> respTask1;
Task<byte[]> respTask2;
byte[] resultdata;
Uri reqUri = new Uri(query.ToString());
HttpRequestMessage webreq = new HttpRequestMessage(HttpMethod.Get, reqUri);
respTask1 = myClient.GetAsync(webreq.RequestUri, HttpCompletionOption.ResponseHeadersRead);
//only retrieve the headers at this stage, stream data will be retrieved below
httpmsg = respTask1.Result;
respTask2 = httpmsg.Content.ReadAsByteArrayAsync();
//now retrieve the response data in a second task
resultdata = respTask2.Result;
在“404 Not Found”的情況下,此代碼既不會引發 AggregateException 也不會引發 HttpRequestException,因此在這兩種情況下都沒有響應 stream 沒有問題。 “404 Not Found”代碼在響應標頭中(我認為它是 StatusCode 標頭),相關的響應 stream 在字節數組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.