首页 > 解决方案 > 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 发布的值?

标签: c#xmlasp.net-web-api

解决方案


您需要将命名空间作为属性提供给 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; }
}

推荐阅读