Async HttpWebRequest catch WebException



我正在尝试从异步HttpWebRequest中捕获WebException以从 API 读取 soap:fault。但它抛出了AggregateException.有没有办法为异步HttpWebRequest捕获WebException

public async Task<XDocument> GetXmlSoapResponseAsync(string soapRequestURL, string xmlData)
    {
      try
      {
        //create xml doc
        XmlDocument doc = new XmlDocument();
        //load xml document frtom xmlData
        doc.LoadXml(xmlData);
        //creta web request
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(soapRequestURL);
        req.ContentType = "text/xml";
        req.Accept = "text/xml";
        req.Method = "POST";
        //GetRequestStream from req
        Stream stm = req.GetRequestStream();
        doc.Save(stm);
        stm.Close();
        Task<WebResponse> task = Task.Factory.FromAsync(
        req.BeginGetResponse,
        asyncResult => req.EndGetResponse(asyncResult),
        (object)null);
        var response = task.Result;
        return await task.ContinueWith(t => ReadStreamFromResponse(response,stm, soapRequestURL,xmlData));
      }
      catch (WebException webException)
      {
        LogWebException(webException, soapRequestURL, xmlData);
        return null;
      }
    }

更改此内容

var response = task.Result;

对此

var response = await task;

await返回任务的结果解开AggregateException包(如果有的话)。


此外,.Result阻塞当前线程,直到结果可用,这可能不是您想要的,否则您只会使用阻塞GetResponse,而不是异步BeginGetResponseEndGetResponse

此外,您甚至不需要这两种方法。还有一个更好的 - GetResponseAsync

使用这个:

var response = await req.GetResponseAsync();

取而代之的是:

Task<WebResponse> task = Task.Factory.FromAsync(
req.BeginGetResponse,
asyncResult => req.EndGetResponse(asyncResult),
(object)null);
var response = task.Result;

相关内容

  • 没有找到相关文章

最新更新