0

My web api is returning a set of objects which are differ from the Domain object. Forexample, I my domain has an Employee class but I don't want to expose all the members of the Employee class in my api so I created another class called EmployeeApiModel.

Now my WebApi is returning a List of EmployeeApiModel but I want to be able to specify the name to which it should serialize to. That is instead of <EmployeeApiModel> tag in the xml, I want to get <Employee> but without changing the fact that the underlying class which is being serialized is EmployeeApiModel.

How can I achieve this?

4

2 回答 2

3

从技术上讲,Web Api 基于内容协商机制同时支持 json 和 xml,Json 是默认格式,如果要接收 xml,只需加上 header:

接受:应用程序/xml

要了解更多内容协商,请访问

由于您希望您的 api 同时支持 json 和 xml,因此您应该使用 DataContract 和 DataMember 属性对您的模型进行序列化:EmployeeApiModel,例如:

[DataContract(Name = "Employee")]
public class EmployeeApiModel
{
    [DataMember(Name = "Name2")]
    public string Name { get; set; }

    [DataMember]
    public string Email { get; set; }
}

在此博客文章中查看更多信息

于 2012-08-09T15:22:23.917 回答
0

您可以使用各种 Attribute 标签来控制序列化 XML 的输出。

[XmlRoot("Employee")]
Public class EmployeeApiModel
{
    [XmlElement("fname")]
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int age { get; set; }
}

这将产生如下 XML:

<Employee>
    <fname>John</fname>
     <LastName >Smith</LastName >
    <age>24</age>  
</RootElementsName>

您可以在此处阅读有关各种 XML 修饰符的更多信息:http: //msdn.microsoft.com/en-us/library/e123c76w

如果您想对 JSON 使用现有的 XML 修饰符,请查看这篇文章:将 .Net 对象序列化为 json,使用 xml 属性控制

于 2012-08-09T14:58:18.283 回答