2016-09-01 39 views
0

我有以下的接口定义C#WCF服务:嵌套异常的返回类型为WCF服务

[ServiceContract] 
    [ServiceKnownType(typeof(Exception))] 
    [ServiceKnownType(typeof(ArgumentException))] 
    [ServiceKnownType(typeof(ArgumentNullException))] 
    public interface IDataExchangeService 
    { 
     [OperationContract] 
     Exception DoSomething(bool someParam); 
    } 

正如你可以看到,该方法应该或者返回NULL(当方法的执行成功)或包含任意错误消息的异常。该方法已经用ServiceKnownType属性声明,以避免在向客户端返回异常实例时出现错误。这仅适用于返回的异常的类型等于已声明的ServiceKnownTypes之一并且InnerException为NULL的情况。但是,如果我回到一个例外,多数民众赞成有,例如,一个ArgumentException如的InnerException,我得到的错误说,ArgumentException的类型是未知的:

There was an error while trying to serialize parameter http://tempuri.org/:DoSomething. The InnerException message was 'Type 'System.ArgumentNullException' with data contract name 'ArgumentNullException:http://schemas.datacontract.org/2004/07/System' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.'. 

我有2个问题,现在:

  1. 如何我可以使它可以返回任何类型的异常,而无需将每种可能的类型声明为ServiceKnownType属性?
  2. 是否可以使用任意InnerException类型返回嵌套异常?

回答

0

你可以绝对捕获所有异常并将它们变成FaultException。 ATLEAST你的代码不会拆掉。另一个方法是实现IErrorHandler的服务类,并提供故障exception.Take看看这个IErrorHandler Behavior

+0

的FaultException不解决我的问题,因为它只是另一种类型的异常。在这种情况下返回Exception或FaultException没有区别,因为这两个变体都可以正常工作(除了Exception声明的问题,即Exception不能有InnerException)。 – Cleo

+0

当我尝试返回一个FaultException时,它也不起作用(但没有将该类型添加为ServiceKnownType!)。但是我在客户端得到另一个异常:“底层连接已关闭:接收时发生意外错误。” 猜猜我必须坚持一个通用的“例外”作为返回类型的时刻... – Cleo