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"), 
FaultMessages.NoRouteFoundMessage);
 
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 'http://schemas.datacontract.org/2004/07/System.ServiceModel.Channels'..
Encountered 'Element'  with name 'Fault', namespace 'http://www.w3.org/2003/05/soap-envelope'.

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:

 

Assert.IsTrue(msg.IsFault);
 
var fault = MessageFault.CreateFault(msg, 100000);
 
Assert.IsNotNull(fault);
Assert.IsNotNull(fault.Reason.Translations);
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.

No comments: