【问题标题】:How to obtain a web response exception stream when returned exception is "AggregateException" instead of "WebException"当返回的异常是“AggregateException”而不是“WebException”时如何获取 Web 响应异常流
【发布时间】: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#


    【解决方案1】:

    看来我找到了解决上述问题的方法。我将示例 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,因此在这两种情况下都没有响应流是没有问题的。 “404 Not Found”代码在响应头中(我认为是 StatusCode 头),相关的响应流在字节数组中。

    【讨论】:

      猜你喜欢
      • 2012-06-08
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多