Kei*_*ith 9 .net rest wcf channelfactory protocolexception
我有.Net WCF客户端使用的REST服务.
遇到错误时,REST服务返回HTTP 400 Bad Request,其响应主体包含JSON序列化详细信息.
如果我使用Fiddler,Javascript或直接从C#执行请求,我可以在发生错误时轻松访问响应正文.
但是,我正在使用ChannelFactory具有6个非常复杂的接口的WCF .此代理抛出的异常始终为a ProtocolException,没有有用的详细信息.
当我收到此错误时,有没有办法获得响应正文?
更新
我意识到使用.Net有很多不同的方法可以做到这一点,还有其他方法可以获得错误响应.他们知道但不回答这个问题很有用.
我们正在使用的REST服务将发生变化,当它们执行时,复杂的接口会更新.使用ChannelFactorywith new接口意味着我们将获得编译时(而不是运行时)异常,并使这些代码更容易维护和更新.
使用WCF通道时,有没有办法让错误HTTP状态的响应体?
小智 5
您可以检索异常详细信息,如下所示:
Exception innerException = exception.InnerException;
WebException webException = innerException as WebException;
HttpWebResponse response = webException.Response as HttpWebResponse;
string statusDescription = response.StatusDescription;
HttpStatusCode statusCode = response.StatusCode;
Run Code Online (Sandbox Code Playgroud)
的InnerException的ProtocolException将是一个WebException。您可以从中获取HttpWebResponse并调用GetResponseStream以读取实际的响应正文。(请记住在阅读之前寻找流的开头)。
var webException = (WebException) protocolException.InnerException;
var response = (HttpWebResponse) webException.Response;
var responseStream = response.GetResponseStream()
responseStream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(responseStream);
var responseContent = reader.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)
不要使用 ChannelFactory :-) 说真的。为什么要创建 REST 接口然后使用 WCF 客户端代理。使用REST服务有什么好处?为什么不直接使用 wsHttpBinding 呢?使用 REST 入门工具包中的 HttpClient 类,您可以发出标准 HTTP 请求,然后使用 DataContractSerializer 反序列化响应。
例如
var httpClient = new HttpClient();
var content = httpClient.Get("http://example.org/customer/45").Content;
var customer = content.ReadAsDataContract<Customer>()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6056 次 |
| 最近记录: |