我使用PUT将XML发送到WebAPI以向我的数据库添加记录。每个类都有[DataContract]
属性,其字段具有[DataMember]
属性。这样做的原因是我们不想将实际的类型名称暴露给最终用户。
我的班级结构如下:
public class Customer
{
[DataMember(Name = "CustomerId")]
public int CustomerId { get; set; }
[DataMember(Name = "CustomerType")]
public CustomerTypeDTO CustomerTypeDto { get; set; }
[DataMember(Name = "Name")]
public string Name { get; set; }
[DataMember(Name = "Orders")]
public List<OrderDTO> Orders { get; set; }
}
[DataContract(Namespace = "", Name = "CustomerType")]
public class CustomerTypeDTO
{
[DataMember(Name = "CustomerTypeId")]
public int CustomerTypeId { get; set; }
[DataMember(Name = "TypeCode")]
public string TypeCode { get; set; }
}
[DataContract(Namespace = "", Name = "Order")]
public class OrderDTO
{
[DataMember(Name = "OrderId")]
public int OrderId { get; set; }
[DataMember(Name = "CustomerId")]
public int CustomerId { get; set; }
[DataMember(Name = "Amount")]
public decimal Amount { get; set; }
}
我的Web Api控制器接受XML为:
<ArrayOfCustomer>
<Customer>
<CustomerId>1</CustomerId>
<Name>Customer A</Name>
<CustomerType>
<CustomerTypeId>1</CustomerTypeId>
<TypeCode>Corporate</TypeCode>
</CustomerType>
<Orders>
<Order>
<OrderId>1</OrderId>
<CustomerId>1</CustomerId>
<Amount>100000.00</Amount>
</Order>
</Orders>
</Customer>
</ArrayOfCustomer>
收到XML后,CustomerType
成员始终为null。我花了很多时间来调查这个问题,但没有用。
我的控制器方法如下:
[RoutePrefix("customers")]
public class CustomerController : ApiController
{
[Route("putcustomer")]
public async Task<HttpResponseMessage> Put(List<Customer> customers)
{
var orders = customers[0].Orders;
return Request.CreateResponse(HttpStatusCode.OK);
}
}
答案 0 :(得分:1)
您必须告诉WebApi
如何序列化您发送的xml。
在您的情况下,您发送Xml without any namespaces
,因此绑定为空。
尝试发送如下的XML数据:
<ArrayOfCustomer xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Customer>
<CustomerId>20</CustomerId>
<CustomerType>
<CustomerTypeId>221</CustomerTypeId>
<TypeCode>test</TypeCode>
</CustomerType>
<Name>test</Name>
<Orders />
</Customer>
</ArrayOfCustomer>
我使用上面的xml测试了你的解决方案并且它正常工作:)尝试阅读有关如何在WebApi及其默认序列化器中完成序列化的更多信息。
您可以结帐的一些建议(适用于WebApi):
IHttpActionResult
,而不是使用HttpResponse
。 (见2.0版)custom xml serializer
。阅读更多here