gpt4 book ai didi

WCF Rest 服务错误处理和 WebChannelFactory

转载 作者:行者123 更新时间:2023-12-04 20:17:29 25 4
gpt4 key购买 nike

根据我的理解,以下内容应该从 WCF Rest 服务正确抛出自定义错误:

[DataContract(Namespace = "")]
public class ErrorHandler
{
[DataMember]
public int errorCode { get; set; }

[DataMember]
public string errorMessage { get; set; }
} // End of ErrorHandler

public class Implementation : ISomeInterface
{
public string SomeMethod()
{
throw new WebFaultException<ErrorHandler>(new ErrorHandler()
{
errorCode = 5,
errorMessage = "Something failed"
}, System.Net.HttpStatusCode.BadRequest);
}
}

在 Fiddler 这似乎有效,我得到以下原始数据:
HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Length: 145
Content-Type: application/xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Set-Cookie: ASP.NET_SessionId=gwsy212sbjfxdfzslgyrmli1; path=/; HttpOnly
X-Powered-By: ASP.NET
Date: Thu, 03 May 2012 17:49:14 GMT

<ErrorHandler xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><errorCode>5</errorCode><errorMessage>Something failed</errorMessage></ErrorHandler>

但现在在我的客户端我有以下代码:
WebChannelFactory<ISomeInterface> client = new WebChannelFactory<ISomeInterface>(new Uri(targetHost));

ISomeInterface someInterface = client.CreateChannel();
try
{
var result = someInterface.SomeMethod();
}
catch(Exception ex)
{
// Try to examine the ErrorHandler to get additional details.
}

现在,当代码运行时,它命中了一个 System.ServiceModel.ProtocolException消息“远程服务器返回意外响应:(400) 错误请求。”。看来此时我还没有办法看到ErrorHandler的详细信息。有没有人遇到过这个?有没有办法在这一点上获得 ErrorHander 的详细信息?

最佳答案

WebChannelFactoryChannelFactory只会向您披露通用的 CommunicationException .您将需要使用 IClientMessageInspector行为或依赖 WebRequest返回实际错误。

对于 IClientMessageInspector方法 - 参见 this blog entry 中的评论.

对于 WebRequest方法,你可以通过以下方式来捕捉WebException .

try { }
catch (Exception ex)
{
if (ex.GetType().IsAssignableFrom(typeof(WebException)))
{
WebException webEx = ex as WebException;
if (webEx.Status == WebExceptionStatus.ProtocolError)
{
using (StreamReader exResponseReader = new StreamReader(webEx.Response.GetResponseStream()))
{
string exceptionMessage = exResponseReader.ReadToEnd();
Trace.TraceInformation("Internal Error: {0}", exceptionMessage);
}
}
}
}

关于WCF Rest 服务错误处理和 WebChannelFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10436951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com