Reputation: 1407
I am trying to catch WebException
from asynchronous HttpWebRequest
to read soap:fault from api. But it throws AggregateException
. Is there a way to catch WebException
for Async HttpWebRequest
?
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;
}
}
Upvotes: 0
Views: 1453
Reputation: 68670
Change this
var response = task.Result;
to this
var response = await task;
await
returns the result of the task or unwraps the AggregateException
, if any.
Also, .Result
blocks the current thread until the result is available, and that's probably not what you want, otherwise you'd just be using the blocking GetResponse
, instead of the async BeginGetResponse
and EndGetResponse
.
Also, you don't even need those two methods. There's a better one - GetResponseAsync
Use this:
var response = await req.GetResponseAsync();
Instead of this:
Task<WebResponse> task = Task.Factory.FromAsync(
req.BeginGetResponse,
asyncResult => req.EndGetResponse(asyncResult),
(object)null);
var response = task.Result;
Upvotes: 3