我今天自己遇到了这个。解决方案是使用不继承自 FaultContract 中的 Exception 的对象。如果您查看有关FaultException和FaultContract的 MSDN 文档,您将看到官方示例使用普通类(具有 DataContact 属性)而不是扩展 FaultException.Detail 异常的类。我不确定为什么异常会导致添加服务引用失败,但我怀疑它与序列化或检索自定义异常的类型信息有关。我已经在示例实现之前和之后包含了以演示工作方法。
之前(没有工作):
[ServiceContract]
public interface IMyService
{
[OperationContract]
[FaultContract(typeof(MyException))]
MyResults MyServiceOperation(string myParameter);
}
[Serializable]
public class MyException : Exception
{
public string CustomData { get; set; }
}
[ErrorHandlerBehavior(typeof(MyErrorHandler))]
public class MyService : IMyService
{
public MyResults MyServiceOperation(string myParameter)
{
...
throw new MyModelException { CustomData = "42" };
...
}
}
public class MyErrorHandler : IErrorHandler
{
public bool HandleError(Exception error) { return false; }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
try { throw error; }
catch (MyModelException ex)
{
var faultEx = new FaultException<MyException>(new MyException { CustomData = ex.CustomData });
fault = Message.CreateMessage(version, faultEx.CreateMessageFault(), faultEx.Action);
}
catch { /* Supress all others */ }
}
}
之后(工作):
[ServiceContract]
public interface IMyService
{
[OperationContract]
[FaultContract(typeof(MyFault))]
MyResults MyServiceOperation(string myParameter);
}
[DataContract]
public class MyFault
{
[DataMember]
public string CustomData { get; set; }
}
[ErrorHandlerBehavior(typeof(MyErrorHandler))]
public class MyService : IMyService
{
public MyResults MyServiceOperation(string myParameter)
{
...
throw new MyModelException { CustomData = "42" };
...
}
}
public class MyErrorHandler : IErrorHandler
{
public bool HandleError(Exception error) { return false; }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
try { throw error; }
catch (MyModelException ex)
{
var faultEx = new FaultException<MyFault>(new MyFault { CustomData = ex.CustomData });
fault = Message.CreateMessage(version, faultEx.CreateMessageFault(), faultEx.Action);
}
catch { /* Supress all others */ }
}
}
资料来源:Max Strini,感谢他使用他的代码并帮助找到解决此问题的方法。