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

时间:2015-07-13 16:03:25

标签: c# .net xml webclient uploadstring

我使用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响应是什么。

我需要做的是将XML数据发布到Async中的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吗?

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:

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

     }