Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can WCF REST services support deserialisation of XML messages with arbitrary element order?

Tags:

rest

c#

wcf

I have a C# WCF REST Service which allows the addition of a bookmark, by sending an HTTP POST request with the bookmark serialised in XML. I have specified the operation contract for the service, which picks up the xml and automatically deserialises the object for me. My problem is that the deserialisation only works correctly if the XML elements in the request are given in alphabetical order, and the values for any elements that are out of order are not populated.

This behaviour has been reported elsewhere.

I find this to be quite unsatisfactory; I consider the requirement to construct the XML in a specific order to be unnecessary, and a major headache. This is a major requirement to add to all clients of the service, and a source of potentially difficult problems to debug.

Is it possible to direct WCF to be XML element order agnostic?


Some further details for clarification purposes:

My operation contract looks like this:

[OperationContract]
[WebInvoke(Method="POST", UriTemplate = "/{username}/bookmarks", ResponseFormat = WebMessageFormat.Xml)]
public void PostBookmark(string username, RestBookmark newBookmark);

The RestMessage looks as follows:

[DataContract(Name = "Bookmark", Namespace = "")]
public class RestBookmark
{   
    [DataMember]
    public string BookmarkMd5 { get; set; }

    [DataMember]
    public string Url { get; set; }

    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string Title { get; set; }

    [DataMember]
    public string Description { get; set; }
}

If I send the following XML message, then only the UserName property of the RestMessage object will be populated when PostBookmark() is invoked:

<?xml version="1.0"?><Bookmark><UserName>nick.street</UserName><Url>http://www.stackoverflow.com</Url><BookmarkMd5>f184eb3347cf94f6ce5f5fc2844e3bdd</BookmarkMd5><Description>Developer Forum</Description><Title>Stack Overflow</Title></Bookmark>
like image 790
Nick Street Avatar asked Nov 25 '22 22:11

Nick Street


1 Answers

The DataContractSerializer requires strict ordering of elements for both versioning and performance reasons.

There are some options I can think of,

  1. write a message inspector to re-order the raw XML elements in AfterReceivedRequest before it's deserialized by dataContractSerializer.

  2. using the XmlSerializer for your services.

  3. develop HTTP raw XML message process service instead.

  4. pass the object as a dictionary (not recommended)

like image 126
Ray Lu Avatar answered Dec 23 '22 13:12

Ray Lu