0
我試圖從異步HttpWebRequest
中捕獲WebException
以從soap讀取soap:fault。但它會拋出AggregateException
。有沒有辦法趕上WebException
的異步HttpWebRequest
?Async HttpWebRequest catch 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;
}
}
感謝快速完美的答案,並與優化我的代碼等待req.GetResponseAsync();.我對這個異步的東西很陌生,我必須閱讀更多才能正確理解它。非常感謝! – sanjeev
@sanjeev沒問題。 「BeginXX」和「EndXX」方法對是[APM-異步編程模型]的一部分(http://msdn.microsoft.com/zh-cn/library/ms228963(v = vs.110).aspx ),它們在.NET 4.5之前非常有用。現在,隨着異步/等待的引入,在大多數情況下,你最好使用'XXAsync'對應。 – dcastro
好的,謝謝dcastro! – sanjeev