问题描述
我正在从一个标准的MVC 4的WebAPI项目如下回应;
I am getting the following response from a standard MVC 4 WebApi project;
<ArrayOfProduct xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Product>
<Id>1</Id>
<Name>Tomato Soup</Name>
<Category>Groceries</Category>
<Price>1</Price>
</Product>
</ArrayOfProduct>
我试图让这个返回
I am trying to make it so that it returns
<Products>
<Product>
<Id>1</Id>
<Name>Tomato Soup</Name>
<Category>Groceries</Category>
<Price>1</Price>
</Product>
</Products>
我发现有很多参考的各种方法,理应解决这个问题,没有工作;
I have found many reference to various methods that supposedly solve this, none work;
更改默认的序列化器无法正常工作。
Changing the default serializer does not work.
创建客户为串行产品
不起作用。
Creating a customer serializer for Product
does not work.
创建具有新类列表&LT;产品方式&gt;
曝光用合适的XmlRoot和属性的XmlElement不工作
Creating a new class that has List<Product>
exposed with suitable XmlRoot and XmlElement attributes does not work.
添加 Datacontract
属性不能正常工作。
Adding Datacontract
attributes does not work.
添加 CollectionDatacontract
属性不能正常工作。
Adding CollectionDatacontract
attributes does not work.
这看起来是如此简单每个人,除了我!
This appears to be so simple to everyone else, except me!
推荐答案
尝试使用XmlSeriazlier来代替:
Try using the XmlSeriazlier instead:
config.Formatters.XmlFormatter.UseXmlSerializer = true;
然后再试试定义,从产品的集合派生的类,然后用[XmlRoot(产品)的元素名称从'ArrayOfProduct到产品重命名。
And then try defining a class that derives from the collection of Product, and use [XmlRoot("Products")] to rename the element name from 'ArrayOfProduct' to 'Products'.
例如,而不是使用列表,使用类产品:
For example, instead of using List, use the class Products:
[XmlRoot("Products")]
public class Products : List<Product> { }
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public double Price { get; set; }
}
ApiController的行动:
ApiController's action:
public Products Get()
{
return new Products()
{
new Product()
{
Id = 1,
Name = "Tomato Soup",
Category = "Groceries",
Price = 1
}
};
}
这篇关于删除&LT; ArrayOf。从MVC的Web API响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!