问题
I have a question on how to send a custom exception as FaultException. It works when I use a system Exception like ArgumentException, but if I change it to my custom exception "TestException" it fails. I can’t get the configuration for the service reference, when I try to add it.
Works:
[OperationContract]
[FaultContract(typeof(ArgumentException))]
[TransportChannel TestMethod ();
public Void TestMethod()
{
throw new FaultException<ArgumentException>(new ArgumentException("test"), new FaultReason("test"));
}
Doesn’t work:
[OperationContract]
[FaultContract(typeof(TestException))]
[TransportChannel TestMethod ();
public Void TestMethod()
{
throw new FaultException<TestException>(new TestException("test"), new FaultReason("test"));
}
My “TestException” looks like this:
[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) { }
}
I guess I have to add a DataContract on the custom object, but I don’t understand why it won’t work like it is, since the ArgumentException works. Can someone enlighten me?
Thanks for help :)
回答1:
You do need to mark it with [DataContract] as described at this page: http://msdn.microsoft.com/en-us/library/ms576199.aspx.
I'm assuming (but don't know for sure) that ArgumentException works because it's known on both sides of the wire (assuming you're using .NET on each side). Without declaring your exception as a DataContract, it can't be described and serialized/deserialized correctly by the DataContractSerializer.
回答2:
You certainly need to Mark it as DataContract. It is a custom type, which the other side (your client) does not know.
来源:https://stackoverflow.com/questions/5717231/faultexception-and-custom-exception-wcf