Thursday, August 18, 2011

WCF REST - Two things made me wondering 2 or 3 days (stream.Position = 0 and WebMessageBodyStyle.Bare

Recently I developed one WCF REST service which has to be consumed in Silverlight 4.0. Since it is a WCF REST service, we will be dealing with JSON or XML format. But my customer wanted the support for object/contract as well [Don't ask me why not use simple WCF :) ]. So I did implement Datacontract Serialization. I was facing these 2 issues and looking throught web for answers. Finally after 2 days, the solution just struck in my mind.

Issue 1:
Root element is missing

I had the following code for deserialization.

XDocument doc = XDocument.Load(result);
MemoryStream str = new MemoryStream();
doc.Save(str);

DataContractSerializer serializer = new DataContractSerializer(typeof(EntityTypesCollection));
EntityTypesCollection typeColls = (EntityTypesCollection)serializer.ReadObject(str); //I was receiving the error "Root element is missing" here

I kept checking, what am I doing wrong... Finally after some brain crunches, finally figured out that we need to position the stream to 0.
str.Position = 0;

Voila, Issue 1 solved. Now the second issue.

Issue 2:
Response XML was wrapped like this;
<operation_response><operation_result>[Actual Result]</operation_result></operation_response>

I found a lot of complicated approaches to the simple 2 lines of deserialization code. Like filtering out the XElements from the response and through LINQ building back the contract.

Suddenly I noticed that, I mentioned the BodyStyle as WebMessageBodyStyle.Wrapped. This when I changed to WebMessageBodyStyle.Bare, Voila the response XML just came out like I wanted. Finally, the simple 2 lines of deserialization code worked..

So folks, be aware these 2 issues when you work witn WCF REST and serialization/deserialization.