的ASP.NET Web API - XML首字母大写 [英] ASP.NET Web API - XML in camelcase

查看:333
本文介绍了的ASP.NET Web API - XML首字母大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用的Web API和MVC 4,并且都要求有骆驼情况下,我们的请求/响应。

We are using Web API with MVC 4, and are required to have our request/responses in camel case.

我们已经做了对JSON具有以下code:

We have done that for JSON with the following code:

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

同样的code遗憾的是不为工作 XmlMediaTypeFormatter

什么是最优雅的解决办法骆驼的情况下格式化XML?

What would be the most elegant workaround to format XML in camel case?

推荐答案

解决方法1:使用XmlSerializer的

Solution 1 : Using XmlSerializer

如果你需要匹配现有的XML模式(在你的情况一样使用骆驼情况)。您应该使用XmlSerializer类有在生成的XML更多的控制。
要使用XmlSerializer的,你需要设置下面的配置在您的API控制器类的Global.asax文件或构造。

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;

进行此更改后,您可以添加[DataContract]和[DataMember]标注为你的实体,这将影响到XML结果。

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;
}

解决方案2:创建自定义XML格式化类

Solution 2 : Creating custom XML Formatter class

您应该开发自己的媒体格式化类,并将其设置为默认XML formatter.It将需要很长时间和精力比的解决方案1。
为了能够创建一个自定义格式的媒体类请参见下面的链接。

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

这篇关于的ASP.NET Web API - XML首字母大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆