WCF:无法处理客户端上的FaultException <t> </t>

时间:2011-11-24 11:51:20

标签: .net wcf exception-handling

我想从WCF服务器抛出自定义异常,但它对我的客户端不起作用。我做了什么:

我的自定义例外:

[DataContract]    
public class MyCustomException
{
  [DataMember]
  public string MyField { get; set; }
}

我的WCF服务合同

[ServiceContract]    
public interface IMyService
{
       [OperationContract]
       [FaultContract(typeof(MyCustomException))]
       bool Foo();
}

我的WCF服务的全局异常处理程序(此代码在调用Foo时命中):

public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
{
  var ex = new MyCustomException { MyField = "..." };
  var fe = new FaultException<MyCustomException>(
                    ex,
                    new FaultReason("reason"),
                    FaultCode.CreateSenderFaultCode(new FaultCode("some-string")));

  var flt = fe.CreateMessageFault();
  fault = Message.CreateMessage(
    version,
    flt,
    string.Empty
  );        
}

然后......我的客户:

try
{
   Create channel factory and call Foo
}
catch(FaultException<MyCustomException> ex)
{
  // OOOPS! It doesn't work!!! 
}
catch(FaultException ex)
{
  // This block catches exception 
}

这里有什么不对?先感谢您!

1 个答案:

答案 0 :(得分:2)

我在ProvideFault方法中找到了问题:

fault = Message.CreateMessage(
    version,
    flt,
    string.Empty
  ); 

应替换为

fault = Message.CreateMessage(
    version,
    flt,
    fe.Action
  ); 

现在一切都好!