获取WebClient的错误,因为字符串 [英] Get WebClient errors as string

查看:385
本文介绍了获取WebClient的错误,因为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个诊断工具,测试Web服务。

I have a diagnostic tool which tests a web service.

我要的工具,当有问题要上报,这样我已经部署了服务与问题该合同对其进行测试。

I want the tool to report when there are problems, so I have deployed a service with a problem with the contract to test it.

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

When I browse to it I get a page with a very descriptive message such as:

这是ExceptionDetail,可能是由IncludeExceptionDetailInFaults = TRUE,
,其值是创建:出现异常的调用一个WSDL

System.InvalidOperationException出口扩展:结果
System.ServiceModel.Description.DataContractSerializerOperationBehavior
合同:DataContract类型XXX不能因为类型
XXX被添加到DataContractSet与命名空间中的数据相同协定名称XXX XXX是已经存在
和合同并不等同等。

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:

and get this useful error message as a string, however I get the following WebException:

远程服务器返回错误:(500)内部服务器错误

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

我怎样才能得到我在浏览器中收到了同样的错误消息作为字符串返回,没有得到一个例外呢?

How can I get the same error message I received in the browser returned as a string, without getting an exception?

感谢。

推荐答案

您必须捕获异常,并读取响应。

You have to catch the exception and read the response.

catch (WebException exception)
{
  string responseText;

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

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

这篇关于获取WebClient的错误,因为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆