c# - XML 发布到 Web api 映射为 null
问题描述
在 webapiconfig 我有
config.Formatters.XmlFormatter.UseXmlSerializer = true;
控制器
public class PersonController : ApiController
{
[HttpPost]
public void Submit([FromBody]Person person)
{
// Do something with person
}
}
案例 1(作品,即人对象从发布的 XML 中获取值)当我像这样发布 XML
<Person>
<Name>Alex</Name>
<Country>USA</Country>
</Person>
案例 2(不起作用,即 person 对象为空)当我像这样发布 XML
<?xml version="1.0 encoding="utf-8"?>
<Person xmlns:xsd="http:www.w3.org/2001/XMLScheme"
xmlns:xsi="http:www.w3.org/2001/XMLScheme-instance">
<Name>Alex</Name>
<Country>USA</Country>
</Person>
我应该怎么做才能让案例 2 的人员对象获取 XML 发布的值?
解决方案
您需要将命名空间作为属性提供给 node Person
。
所以使用下面的类结构让它与案例 2 一起工作,
[XmlRoot("Person")]
public class Person
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Country")]
public string Country { get; set; }
[XmlAttribute("xsd", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Xsd { get; set; }
[XmlAttribute("xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Xsi { get; set; }
}
推荐阅读
- android - 在Android中使用双向数据绑定时如何修复找不到符号view-model-name-BindingImpl
- javascript - 如何获取项目在实时数据库中的位置
- regex - 如何使 javascript 正则表达式在 postgresql regexp_matches 中工作?
- php - 访问数组时,PHP在字符串上爆炸抛出NULL对象
- awk - 查找每个 xyz 条目和最后一个条目之间的距离
- node.js - 如何在我的网站上安全地存储用于第 3 方服务的密码
- performance - 如何编写优化的 DAX 度量以按属性按两组聚合值
- r - 如何使用绘图设备大小缩放 ggplot annotation_custom 图层?
- spring - 节点找不到contractState(Corda,Spring)
- android - Android Studio 中的 10000x11866 大 .PNG 图像仍然模糊