Thursday, December 2, 2010

WCF: Parse a Fault from a raw message

Here is the thing I bumped into few weeks ago. When writing a wcf router, I had to parse a raw message as a fault. On the server it would look like:

var fault = MessageFault.CreateFault(new FaultCode("RoutingError"), 
return Message.CreateMessage(requestMessage.Version, fault, "*");

And then, on the client one may expect:

MessageFault fault = msg.GetBody<MessageFault>();

Alas, it doesn’t work like this giving an exception:

System.Runtime.Serialization.SerializationException : Expecting element 'MessageFault' from 
namespace ''..
Encountered 'Element'  with name 'Fault', namespace ''.

What worked for me in the end was:


var fault = MessageFault.CreateFault(msg, 100000);


where msg is that incoming raw message. And here is a test snippet to show that Reason translations stuff that
came out as a surprise to me Smile:


var fault = MessageFault.CreateFault(msg, 100000);
Assert.IsTrue(fault.Reason.Translations.Count > 0);
Assert.AreEqual(FaultMessages.NoRouteFoundMessage, fault.Reason.Translations[0].Text);


This is it, it was supposed to be a short one Smile.

Post a Comment