Reputation: 27011
I'm using DataContractDeserializer for my WebAPI application.
I have a PostProduct action which accepts a Product object.
public void PostProduct([FromBody] Product product)
{
}
[DataContract(Namespace = "")]
public class Product
{
[DataMember(EmitDefaultValue = false)]
public int Id { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Name { get; set; }
}
By default apparently the xml data must be sent in alphabetical ordering otherwise the Web API engine can't deserialize those properties and leave them as null.
for example, using Fiddler, I'd have to send {0} and {1} is not acceptable:
{0}: works fine
<Product xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Id>1</Id>
<Name>name 1</Name>
</Product>
{1}: fails!
<Product xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Name>name 1</Name>
<Id>1</Id>
</Product>
How to configure WebAPI and DataContractSerializer so that it doesn't care about the Ordering of the properties. It should ideally just try to find a mapping element rather than where the element appears.
Upvotes: 1
Views: 2768
Reputation: 2551
It seems that you can't.
I mean you can't tell DataContractSerializer
not to care about the order.
Here is a nice discussion about it : http://social.msdn.microsoft.com/Forums/vstudio/en-US/a891928b-d27a-4ef2-83b3-ee407c6b9187/order-of-data-members-in-the-xml-string-influences-deserialization-datacontractserializer
If you receive not ordered data you can try to set a XmlSerializer
instead of a DataContractSerializer
, XmlSerializer
doesn't care about order.
Upvotes: 1