We are using Web API with MVC 4, and are required to have our request/responses in camel case.
We have done that for JSON with the following code:
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().Single();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
The same code unfortunately doesn't work for the XmlMediaTypeFormatter
.
What would be the most elegant workaround to format XML in camel case?
Solution 1 : Using XmlSerializer
If you need to match an existing XML schema ( in your case like using camel case. ) You should use XmlSerializer class to have more control over the resulting XML. To use XmlSerializer you need to set below configuration in global.asax file or constructor of your API controller class.
var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;
After making this change you can add [DataContract] and [DataMember] for your entities which will affect XML result.
[DataContract(Name = "USER")]
public class User
{
[DataMember(Name = "FIRSTNAME")]
public string FirstName;
[DataMember(Name = "LASTNAME")]
public string LastName;
}
Solution 2 : Creating custom XML Formatter class
You should develop your own Media Formatter class and set it as a default XML formatter.It will take long time and effort than solution 1. To be able to create a custom media formatter class please see below link.
http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With