I am sending XML using PUT to WebAPI to add record to my database. Each class has the [DataContract]
attribute and its fields have a [DataMember]
attribute. The reason for this that we don't want to expose the actual type name to the enduser.
My class structure is as follows:
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; }
}
My Web Api controller accepts the XML as:
<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>
On receiving the XML, the CustomerType
member is always null. I have spent lot of time to investigate the problem but no avail.
My controller method is as:
[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);
}
}
You have to tell to the WebApi
how to serialize the xml that you send along.
In your case, you are sending Xml without any namespaces
and hence the binding is null.
Try sending your XML data like below:
<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>
I tested your solution with the above xml and it works :) Try reading more on how serialization is done in WebApi and its default serializers.
Some suggestions (for WebApi) that you can checkout:
IHttpActionResult
instead of using HttpResponse
. (See 2.0 release)custom xml serializer
if you need to supply xml without any namespaces. Read more here