今天我碰到了這個。解決方案是使用FaultContract中不從Exception繼承的對象。如果您查看FaultException和FaultContract的MSDN文檔,您將看到官方示例使用普通類(具有DataContact屬性),而不是爲FaultException.Detail擴展Exception的類。我不確定爲什麼Exception導致添加服務引用失敗,但我懷疑它與序列化或檢索自定義異常的類型信息有關。我已經在示例實現之前和之後包括了工作方法。對於使用他的代碼Max Strini和尋找解決方案幫助:
之前(沒有工作):
[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 */ }
}
}
來源這個問題。
您當然認識到,對於.NET以外的任何平臺,Exception都沒有意義? – 2011-02-08 02:26:52
不,但我對它的印象是,WCF框架需要從Exception中引入Inclusion。這也是我認爲是正確的,因爲它始終能夠爲從Exception繼承的自定義異常創建正確的代理類。 – SpoBo 2011-02-15 10:51:20