C# - 发布时捕获 WebException XML 异步

C# - Catch WebException While Posting XML Async

我正在使用 WebClient 发布 XML 数据。

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

当出现错误时,我将其捕获为 WebException,然后我阅读 Stream 以了解 XML 响应是什么。

我需要做的是 post 异步中的 XML 数据到 URL。 所以我改变了功能:

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

我现在如何捕获 WebException 并读取 XML 响应?

我可以扔e.Error吗?

如有任何帮助,我们将不胜感激

我找到了解决方案:

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

     }