2011-08-12 53 views
23

我有一个测试Web服务的诊断工具。获取WebClient错误作为字符串

我希望该工具在出现问题时进行报告,因此我已经部署了一个服务来解决合同问题以对其进行测试。

当我浏览到它,我得到一个网页一个非常描述性信息,例如:

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is: System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension:
System.ServiceModel.Description.DataContractSerializerOperationBehavior contract: DataContract for type XXX cannot be added to DataContractSet since type XXX with the same data contract name XXX in namespace XXX is already present and the contracts are not equivalent etc..

我要的是能够调用:

myErrorMsg = WebClient.DownloadString("MyBadService.svc"); 

,并得到这个有用的错误消息作为字符串,但我得到以下WebException:

The remote server returned an error: (500) Internal Server Error.

我怎样才能得到相同的错误一团糟我在浏览器中收到的年龄以字符串的形式返回,没有发生异常?

谢谢。

+0

500错误意味着您的网站意外终止。 – Zenwalker

回答

54

你必须捕捉异常并阅读回应。

catch (WebException exception) 
{ 
    string responseText; 

    var responseStream = exception.Response?.GetResponseStream(); 

    if (responseStream != null) 
    { 
     using (var reader = new StreamReader(responseStream)) 
     { 
     responseText = reader.ReadToEnd(); 
     } 
    } 
} 
+1

嘿真棒谢谢 – lockstock

+4

如果由于连接错误,名称解析失败等引发WebException,这将炸毁。检查以确保在尝试从它获取流之前有repsonse。 – JamieSee

+0

哈哈!终于找到了解决办法。非常感谢@ccellar – Anand