简体   繁体   中英

Async HttpWebRequest catch WebException

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;
      }

    }

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM