【问题标题】:Capture response when a service returns a 500 error using WCF当服务使用 WCF 返回 500 错误时捕获响应
【发布时间】:2011-06-14 16:40:14
【问题描述】:

我正在使用 REST(使用 WebHttpBinding 和 WebHttpBehavior)从第 3 方 Web 服务获取数据。当我在查询字符串中传递无效参数时,服务会以 500 状态响应并描述问题。响应如下所示:

HTTP/1.1 500 Internal Server Error
Date: Tue, 14 Jun 2011 16:12:48 GMT
... more headers

<Error>Invalid integer value for ID</Error>

我真的很希望能够捕获该错误消息。我的 WCF 客户端如下所示:

public class DataClient : ClientBase<IDataClient>, IDataClient
{
    public DataClient (string endpointAddress)
        : base(new WebHttpBinding(), new EndpointAddress(endpointAddress))
    {
        this.Endpoint.Behaviors.Add(new WebHttpBehavior());
    }

    public string GetData(string id)
    {
        // This is where the exception is thrown
        return base.Channel.GetData(id);
    }
}

当我捕获抛出的异常时,找不到该数据。它只是说,“System.ServiceModel.CommunicationException:内部服务器错误”。

我尝试创建自定义行为并添加了消息检查器,但我的自定义消息检查器代码在引发异常之前没有执行(如果没有引发异常,它会执行)。

【问题讨论】:

  • 你有&lt;serviceDebug includeExceptionDetailInFaults="true"/&gt;在服务web目录的web.config中添加吗?
  • 我只是消费别人服务的客户。我无法控制服务。
  • 您必须联系提供此服务的人员并询问如何获取详细的异常信息。
  • 他已经传递了我想要的信息。我只想知道,“ID 的整数值无效”

标签: c# wcf exception-handling


【解决方案1】:

我终于明白了。创建自定义行为并添加消息检查器是我需要这样做的方式。我只需要在WebHttpBehavior 之前添加我的自定义行为。然后我可以查看整个响应并抛出我自己的异常,其中包含所有数据!

【讨论】:

  • 在 WebHttpBehavior 之前添加自定义行为是什么意思?
  • 实际上,如果在 WebHttpBehavior 上启用 FaultExceptionEnabled,则可以在 WebHttpBehavior 之后添加自定义行为。
【解决方案2】:

(无法让我的测试项目实际发送 HTTP 500,似乎只有在我不希望它发送时才这样做;-)

如果这对您有帮助,请尝试包装您的客户端服务调用并检查调试器中的 response 以查看它是否包含您尝试捕获的错误字符串。

    using (new OperationContextScope(service1.InnerChannel))
    {
        try
        {
            result = service1.GetData("5");
        }
        catch (System.Exception e)
        {
            string msg = e.ToString();
        }
        HttpResponseMessageProperty response = (HttpResponseMessageProperty)
            OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name];
    }

【讨论】:

  • 我意识到这是一个 11 年前的答案,但这对我来说是最优雅的解决方案,并且能够很好地插入我现有的代码中。
猜你喜欢
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-15
  • 2019-10-07
  • 2011-03-02
  • 1970-01-01
相关资源
最近更新 更多