0

我有一个 WCF REST 服务,该服务在客户端上由经典使用:

 WebResponse response = request.GetResponse();

我想拦截服务中出现的任何错误并将它们传递给客户端。默认情况下,当服务中发生异常时,会抛出错误异常并且通道出现故障,因此在客户端上我会收到错误请求。我希望能够向客户端返回 stackstrace 并覆盖行为而不是使通道出错。为此,我实现了 IErrorHandler

 public class ErrorHandler : IErrorHandler
    {
        public bool HandleError(Exception error)
        {

            return true;
        }

        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {

            fault = Message.CreateMessage(version, string.Empty, String.Format("An unknown error has occurred. The error identifier "), new DataContractJsonSerializer(typeof(string)));
            fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
            fault.Properties.Add(HttpResponseMessageProperty.Name, HttpStatusCode.Accepted);

        }
}

问题是即使我在服务上注册它,我也可以调试错误处理程序,但通道仍然有故障,所以我仍然在客户端收到错误的请求。我为客户使用以下工厂:

protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            var host =  base.CreateServiceHost(serviceType, baseAddresses);

            ServiceEndpoint ep = host.AddServiceEndpoint(serviceType, new WebHttpBinding(), "");
            host.Description.Endpoints[0].Behaviors.Add(new WebHttpBehavior { HelpEnabled = true });     
            return host;


        }

问题是如何防止通道在错误处理程序中出现故障。

4

1 回答 1

0

它应该工作。我有同样的情况,我也在 ProvideFault 方法中设置了故障。我唯一能想到的是,我没有看到您创建了一个从中调用 CreateMessageFault() 的 FaultException。

这是一个例子:

public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
{
  // we don't want the communication channel to fault, so we'll provide a general purpose fault with the exception provided.
  var fe = new FaultException(error.Message);
  MessageFault msg = fe.CreateMessageFault();
  fault = Message.CreateMessage(version, msg, "YourActionNamespace");
}
于 2013-07-25T15:58:46.417 回答