FaultException和自定义异常WCF

fau*_*tEx 4 wcf exception-handling exception custom-exceptions faultexception

我有一个关于如何发送自定义异常作为FaultException的问题.当我使用像ArgumentException这样的系统异常时,它可以工作,但是如果我将它更改为我的自定义异常"TestException",它就会失败.当我尝试添加它时,我无法获得服务引用的配置.

作品:

[OperationContract]
[FaultContract(typeof(ArgumentException))]
[TransportChannel TestMethod ();


public Void TestMethod()
{
            throw new FaultException<ArgumentException>(new ArgumentException("test"), new FaultReason("test"));
}
Run Code Online (Sandbox Code Playgroud)

不起作用:

[OperationContract]
[FaultContract(typeof(TestException))]
[TransportChannel TestMethod ();


public Void TestMethod()
{
            throw new FaultException<TestException>(new TestException("test"), new FaultReason("test"));
}
Run Code Online (Sandbox Code Playgroud)

我的"TestException"看起来像这样:

[Serializable()]
public class TestException: Exception
{
    public TestException () : base() { }
    public TestException (string message) : base(message) { }
    public TestException (string message, Exception innerException) : base(message, innerException) { }
    public TestException (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
Run Code Online (Sandbox Code Playgroud)

我想我必须在自定义对象上添加一个DataContract,但我不明白为什么它不会像它一样工作,因为ArgumentException有效.有人可以开导我吗?

感谢帮助 :)

Nat*_*eat 7

您需要使用[DataContract]标记它,如本页所述:http://msdn.microsoft.com/en-us/library/ms576199.aspx.

我假设(但不确定)ArgumentException是有效的,因为它在线的两侧都是已知的(假设你在每一侧都使用.NET).如果不将您的异常声明为DataContract,则DataContractSerializer无法正确描述和序列化/反序列化.