WCF Disable Deserialization Order Sensitivity

Viewed 16928

I have a recurring problem when passing Serialized objects between non-.NET Clients, and .NET WCF Services.

When WCF Deserializes objects, it is strictly dependant upon the order of properties.

That is, if I define my class as:

public class Foo 
{ 
  public int ID { get; set; } 
  public int Bar { get; set; } 
} 

Then WCF Will serialize the object as as:

<Foo>
  <Bar>123</Bar>
  <ID>456</ID>
</Foo>

Note: The properties are serialized in alphabetical order.

If you attempt to Deserialize an object which has the positions of Bar and ID swapped, WCF will treat the incorrectly positioned elements as null.

Whilst I know I can use the DataMember attribute, and force a specific ordering, I want to reduce the number of times I have to debug issues where fields are 'mysteriously' null.

So, my question is: Can you tell the WCF Deserializer to ignore the order of fields, when deserializing objects.

4 Answers

For me, the DataContractSerializer has been my savior with .NET Framework 4.0

When referencing an old asmx web service, we had null values for all the fields that were "after" inserted new fields in the server wsdl. So whenever there were new fields added on server side, that was nullifying several values on client side. This was forcing us into updating our reference in our code to always stick to the server wsdl.

I found two solutions to make our client tolerant to new fields in the xml stream:

  • Either use an old web reference in visual studio (old client code generator for compatibility)
  • Or use a WCF classic reference, but change the serializer in the svcmap file. ClientOptions -> Serializer = "DataContractSerializer" instead of "Auto". I found out that in our case, the "Auto" value was the same as "XmlSerializer" value.
Related