[英]Async HttpWebRequest catch WebException
I am trying to catch WebException
from asynchronous HttpWebRequest
to read soap:fault from api. 我正在尝试从异步
HttpWebRequest
捕获WebException
以从api读取soap:fault。 But it throws AggregateException
. 但是它抛出了
AggregateException
。 Is there a way to catch WebException
for Async HttpWebRequest
? 有没有办法为异步
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;
}
}
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. await
返回任务的结果或解包AggregateException
(如果有)。
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
. 另外,
.Result
阻塞当前线程,直到结果可用为止,而这可能不是您想要的,否则,您将只使用阻塞GetResponse
,而不是异步BeginGetResponse
和EndGetResponse
。
Also , you don't even need those two methods. 另外 ,您甚至不需要这两种方法。 There's a better one -
GetResponseAsync
有一个更好的
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.