Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API - XML in camelcase

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?

like image 715
Schiavini Avatar asked May 30 '13 11:05

Schiavini


1 Answers

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

like image 189
Arkadas Kilic Avatar answered Sep 23 '22 06:09

Arkadas Kilic