0

我有具有以下接口定义的 ac# WCF 服务:

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

如您所见,该方法应该返回 NULL(当方法执行成功时)或包含任意错误消息的异常。该方法已使用 ServiceKnownType-attributes 声明,以避免在向客户端返回异常实例时出错。这仅在返回的异常类型等于声明的 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.'.

我现在有两个问题:

  1. 我怎样才能使它可以返回任何类型的异常,而不必将每个可能的类型声明为 ServiceKnownType 属性?
  2. 是否可以返回具有任意 InnerException 类型的嵌套异常?
4

1 回答 1

0

您绝对可以捕获所有异常并将它们转换为 FaultException。至少你的代码不会崩溃。另一种方法是在你的服务类中实现 IErrorHandler 并提供错误异常。看看这个IErrorHandler Behavior

于 2016-09-01T11:50:24.970 回答