ASP.NET核心API空XML对象



我有一个控制器,它包含POST方法,该方法必须接收XML对象并对其进行反序列化。但经过所有尝试,我总是得到一个空对象,所有属性都设置为null或默认值。

这是代码(很抱歉这个堆,但我认为错误可能在任何一段代码中。(:

订单类别:

[XmlRoot]
public class Order
{
[XmlElement]
public long OrderSource { get; set; }
[XmlElement]
public long Type { get; set; }
[XmlElement]
public decimal DiscountPercent { get; set; }
[XmlElement]
public string PayMethod { get; set; }
[XmlElement]
public int QtyPerson { get; set; }
[XmlElement]
public decimal ChangeAmount { get; set; }
[XmlElement]
public string Remark { get; set; }
[XmlElement]
public Customer Customer { get; set; }
[XmlElement]
public Address Address { get; set; }
[XmlElement]
public string AddressRemark { get; set; }
[XmlElement]
public Phone Phone { get; set; }
[XmlArray(nameof(Products))]
public List<Product> Products { get; set; }

客户类别:

[XmlRoot]
public class Customer
{
[XmlElement]
public string Name { get; set; }
}

地址类别:

[XmlRoot]
public class Address
{
[XmlElement]
public string CityName { get; set; }
[XmlElement]
public string StreetName { get; set; }
[XmlElement]
public string House { get; set; }
[XmlElement]
public string Flat { get; set; }
[XmlElement]
public string Floor { get; set; }
[XmlElement]
public string DoorCode { get; set; }
}

和电话类:

[XmlRoot]
public class Phone
{
[XmlElement]
public string Number { get; set; }
}

这是请求的正文:

<?xml version="1.0" encoding="UTF-8"?>
<Order>
<orderSource>0</orderSource>
<type>0</type>
<discountPercent>0</discountPercent>
<payMethod>string</payMethod>
<qtyPerson>0</qtyPerson>
<changeAmount>0</changeAmount>
<remark>string</remark>
<customer>
<name>asdasd</name>
</customer>
<address>
<cityName>string</cityName>
<streetName>string</streetName>
<house>string</house>
<flat>string</flat>
<floor>string</floor>
<doorCode>string</doorCode>
</address>
<addressRemark>string</addressRemark>
<phone>
<number>string</number>
</phone>
<products>
<name>string</name>
<code>string</code>
<qty>0</qty>
<price>0</price>
</products>
</Order>

请告诉我,我应该在这里更改什么,这样内置的反序列化程序才能正确处理请求?提前感谢

您的问题是XML元素的大小写与XML不匹配。您的属性是用pascal大小写的,但XML是用camel大小写的。不幸的是,XML是区分大小写的。请参阅:XML区分大小写吗?(答案:是(和c#中不区分大小写的XML解析器。

您需要通过设置XmlElementAttribute.ElementName来修复或覆盖属性名称,如XMLDeserializationdons';t使用抽象类,即:

public class Order
{
[XmlElement("orderSource")]
public long OrderSource { get; set; }
// And similarly for all remaining properties

public class Order
{
public long orderSource { get; set; }
// And similarly for all remaining properties

相关内容

  • 没有找到相关文章