首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WCF REST服务IErrorHandler

WCF REST服务IErrorHandler
EN

Stack Overflow用户
提问于 2013-05-17 20:37:52
回答 1查看 619关注 0票数 0

我有一个WCF REST服务,它在客户机上由classical使用:

代码语言:javascript
复制
 WebResponse response = request.GetResponse();

我想截获服务中出现的任何错误,并将它们传递给客户端。根据默认行为,当服务中发生异常时,将抛出faultexception,通道出现故障,因此在客户机上我会收到一个Bad request。我希望能够将stackstrace返回给客户端,并覆盖不会导致通道错误的行为。为此,我实现了IErrorHandler

代码语言:javascript
复制
 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);

        }
}

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

代码语言:javascript
复制
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;


        }

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

EN

回答 1

Stack Overflow用户

发布于 2013-07-25 23:58:46

应该能行得通。我也有同样的情况,我也在ProvideFault方法中设置了错误。我能想到的唯一一件事是,我没有看到您创建了一个调用CreateMessageFault()的FaultException。

下面是一个示例:

代码语言:javascript
复制
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");
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16609243

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档