简体   繁体   English

ASP.NET Web API - camelcase中的XML

[英]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. 我们正在使用带有MVC 4的Web API,并且需要在驼峰的情况下提供我们的请求/响应。

We have done that for JSON with the following code: 我们使用以下代码为JSON做了这个:

var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().Single();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

The same code unfortunately doesn't work for the XmlMediaTypeFormatter . 遗憾的是,相同的代码不适用于XmlMediaTypeFormatter

What would be the most elegant workaround to format XML in camel case? 在camel案例中格式化XML的最优雅的解决方法是什么?

Solution 1 : Using XmlSerializer 解决方案1:使用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. 如果需要匹配现有的XML模式(在您的情况下使用驼峰大小写)。您应该使用XmlSerializer类来更好地控制生成的XML。 To use XmlSerializer you need to set below configuration in global.asax file or constructor of your API controller class. 要使用XmlSerializer,您需要在global.asax文件或API控制器类的构造函数中设置以下配置。

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]和[DataMember],这将影响XML结果。

[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 解决方案2:创建自定义XML Formatter类

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. 您应该开发自己的Media Formatter类并将其设置为默认的XML格式化程序。它比解决方案1需要花费很长时间和精力。要创建自定义媒体格式化程序类,请参阅下面的链接。

http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM