2011-11-24 61 views
0

我想从WCF服务器抛出自定义异常,但它对我的客户端不起作用。我做什么:WCF:无法在客户端上处理FaultException <T>

我的自定义异常:

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

我的WCF服务合同

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

为WCF服务我的全局异常处理程序(此代码击中时富称):

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 
} 

这里有什么问题?先谢谢你!

回答

2

我已经找到了问题ProvideFault方法:

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

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

代替现在一切都OK!