8

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?

3
  • 3
    If you splatter the appropriate XmlAttributes on your classes and their properties the XmlSerializer should respect them and serialize the XML as you'd prefer. Not As clean or easy as the Json way but it may be a resonable solution nonetheless checkout this link for more info msdn.microsoft.com/en-us/library/83y7df3e(v=vs.110).aspx Commented Apr 5, 2014 at 18:22
  • Also checkout this answer as an example stackoverflow.com/a/22493313/1370442 Commented Apr 5, 2014 at 18:25
  • Both XmlSeralizer and XmlFormatter have a broad range of trouble that I severely recommend not using of them and just stick on Json serializes facilities such as Json.net or ServiceStack tools. Commented Apr 7, 2014 at 14:24

1 Answer 1

5
+100

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

Sign up to request clarification or add additional context in comments.

1 Comment

It's unbelievable that nobody made solution 2 open source :( I tried last year to copy the formatter from Microsoft, but it had too many dependencies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.