Search code examples
c#.netxmlwebclientuploadstring

C# - Catch WebException While Posting XML Async


I am POSTING XML data using WebClient.

  public string uploadXMLData(string destinationUrl, string requestXml)
        {
            try
            {

                System.Uri uri = new System.Uri(destinationUrl);
                using (WebClient client = new WebClient())
                {
                    client.Headers.Add("content-type", "text/xml");
                    var response = client.UploadString(destinationUrl, "POST", requestXml); 
                }
            }

            catch (WebException webex)
            {

                WebResponse errResp = webex.Response;
                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);
                    string text = reader.ReadToEnd();
                }
            }
            catch (Exception e)
            { }

            return null;
        }

When there is an error, I catch it as WebException, and I read the Stream in order to know what the XML response is.

What I need to do, is post the XML data to the URL in Async. So I changed the function:

public string uploadXMLData(string destinationUrl, string requestXml)
{
    try
    {

        System.Uri uri = new System.Uri(destinationUrl);
        using (WebClient client = new WebClient())
        {

            client.UploadStringCompleted
       += new UploadStringCompletedEventHandler(UploadStringCallback2); 
            client.UploadStringAsync(uri, requestXml);
        }
    }

    catch (Exception e)
    { }

    return null;
}


void UploadStringCallback2(object sender, UploadStringCompletedEventArgs e)
{            
    Console.WriteLine(e.Error);
}

How can I catch the WebException now and read the XML response?

Can I throw e.Error?

Any help would be appreciated


Solution

  • I found the solution:

       void UploadStringCallback2(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                object objException = e.Error.GetBaseException();
    
                Type _type = typeof(WebException);
                if (_type != null)
                {
                    WebException objErr = (WebException)e.Error.GetBaseException();
                    WebResponse rsp = objErr.Response;
                    using (Stream respStream = rsp.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(respStream);
                        string text = reader.ReadToEnd();
                    }
                    throw objErr;
                }
                else
                {
                    Exception objErr = (Exception)e.Error.GetBaseException();
                    throw objErr;
                }
            }
    
         }