I recently authored a WebApi REST style service in Visual Studio 2015 which is being consumed by various client apps without any problem. Out-of-the-box WebApi services provide JSON and XML formatters, with JSON being the default one. The first clients apps for my service were .NET desktop apps and one written in Xamarin, and they all used the ubiquitous NewtonSoft library to exchange JSON serialized objects in the requests and responses from the service. This usage of JSON to serialize messages between REST services and client apps is a popular and convenient pattern in recent times.
However, I did have an older client app that needed to call my new service, but its coding style was all based on XML and I felt it would be inelegant or impure to add new code that used JSON and the NewtonSoft libraries. Since a WebApi REST service has implicit support for both XML and JSON, this was a good chance to prove that the service was fully functional for XML based clients. By putting
?format=xml in GET urls and adding
Content-Type: application/xml to POST headers the client could override the JSON default serializer and demand XML formatting instead.
Of course it works. I could issues a GET request and the response contains a complex .NET class object serialized as XML. A typical response might look like this:
<AuthenticationData
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/RCS.Licensing.WebApi.Portable">
<Jobs>
<Job>
<CaseLimit>0</CaseLimit>
<Cases>10000</Cases>
<Client i:nil="true" />
--cut--
Note the formatting of the XML which contains interesting namespaces and the use of i:nil to represent null values (which is actually a W3 standard that developers seem to forget). I absent-mindedly tried to use the
XmlSerializer class to deserialize this XML, and after adding the namespace it seemed to be working well ... until I noticed all the i:nil values where coming back as zero-length strings. Clearly I was using the wrong technique.
The I noticed (and remembered, see highlight text above) that the WebApi uses the data contract serializer, not the XML serializer. Simply use
DataContractSerialize ReadObject and the XML coming back in WebApi responses will unwind the way you want.