回答

1

是的,你可以序列化异常并使用WCF返回它们。我写了一个应用程序,WCF客户端需要在服务器上发生真正的异常;不仅仅是一个高水平的故障。

下面是步骤来实现我们所做的:

1 - 声明一个类EncodedException与单一字符串属性

public class EncodedException 
{ 
    public string SerializedException {get;set;} 
} 

2 - 在您的服务合同增加,表明该属性的服务可能会返回一个FaultException异常。

[ServiceContract()] 
public class MyService 
{ 
    [OperationContract] 
    [FaultContract(typeof(EncodedException), 
        ProtectionLevel = ProtectionLevel.EncryptAndSign)] 
    public string Method1(); 
} 

3 - 在您服务实现在所有的服务操作添加一个try/catch:

public void Method1() 
{ 
    try 
    { 
     // some code here 
    } 
    catch(Exception ex) 
    { 
     EncodedException encodedException = Helper.SerializeException(ex); 
     throw new FaulException<EncodedException>(); 
    } 
} 

4 - 在您的客户端代码捕获异常并解开它:

public void someMethod() 
{ 
    try 
    { 
     serviceClient.Method1(); 
    } 
    catch(FaulException<EncodedException> ex) 
    { 
     Exception decodedException = Helper.DeserializeException(ex); 
     throw new decodedException(); 
    } 
} 

5 - 编写助手来序列化/反序列化异常。如果您还需要该部分的帮助,请告诉我。

我希望这会有所帮助。

+0

所以你可以直到我如何使用EntLib4.1来做到这一点 – BigOmar 2009-11-21 09:06:03

0

我不明白为什么不这样做,如果您已经成功创建了一个可以通过经典asmx序列化的对象,那么它在WCF中会很好。