我有一个WCF REST服务,它在客户机上由classical使用:
WebResponse response = request.GetResponse();我想截获服务中出现的任何错误,并将它们传递给客户端。根据默认行为,当服务中发生异常时,将抛出faultexception,通道出现故障,因此在客户机上我会收到一个Bad request。我希望能够将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;
}问题是如何防止通道在错误处理程序中出错。
发布于 2013-07-25 23:58:46
应该能行得通。我也有同样的情况,我也在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");
}https://stackoverflow.com/questions/16609243
复制相似问题