ASP.NET Web API - XML in camelcase

霸气de小男生 提交于 2019-12-23 08:58:27

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/16835100/asp-net-web-api-xml-in-camelcase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!