当作为 XML 发布到 ASP.Net Core 3.1 Web API 时,具有集合属性的 Class 未正确绑定

Class with Collection Properties are not binding properly when posted as XML to ASP.Net Core 3.1 Web API

我正在尝试 post 我的数据作为 XML 到我的 asp.net 核心 3.1 网络 api。但是,集合属性未在我的模型中绑定。

这是我的 class,

public class Test
{
    public int Usrno { get; set; }
    public string PCname { get; set; }

    public List<Best> Best { get; set; }
}

public class Best
{
    public string Hello { get; set; }

    public Worst[] Worst { get; set; }
}

public class Worst
{
    public int Ko { get; set; }

    public Win[] Win { get; set; }
}

public class Win
{
    public string Kiss { get; set; }
}

这是我的POST终点,

[HttpPost]
[Consumes("application/xml")]
[Produces("application/xml")]
public IActionResult Create([FromBody]Test data)
{
    return Created("", data);
}

这是我的 XML 输入,

<?xml version="1.0" encoding="UTF-8"?>
<Test>
    <Usrno>0</Usrno>
    <PCname>string</PCname>
    <Best>
        <Hello>string</Hello>
        <Worst>
            <Ko>0</Ko>
            <Win>
                <Kiss>string</Kiss>
            </Win>
        </Worst>
    </Best>
</Test>

这里是API,

POST方法的截图

这是我在 Startup.cs

中的 ConfigureServices
services
    .AddControllers()
    .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; })
    .AddXmlSerializerFormatters()
    .AddXmlDataContractSerializerFormatters();

我不知道我错过了什么。请协助

尝试在 Best 元素上使用 XmlElementAttribute

XmlElement 属性表示当 XmlSerializer 序列化或反序列化包含它的对象时,public 字段或 属性 代表一个 XML 元素。

C#

public class Test
{
    public int Usrno { get; set; }
    public string PCname { get; set; }

    [XmlElement("Best")]
    public List<Best> Best { get; set; }
}

MVC 的 XmlSerializerInputFormatter 调用 XmlSerializer 反序列化请求的主体,formetter 使用此属性标记 XML 个元素。

xml 序列化中的数组或列表需要两个标签,如 "Names" 和 "Name"。您只有一个标记,因此您需要添加属性 XmlElement。此问题出现在您的 类 中的多个位置。我解决了所有问题。见下文类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);

            XmlSerializer serializer = new XmlSerializer(typeof(Test));
            Test test = (Test)serializer.Deserialize(reader);
        }
    }
    public class Test
    {
        public int Usrno { get; set; }
        public string PCname { get; set; }

        [XmlElement("Best")]
        public List<Best> Best { get; set; }
    }

    public class Best
    {
        public string Hello { get; set; }

        [XmlElement("Worst")]
        public Worst[] Worst { get; set; }
    }

    public class Worst
    {
        public int Ko { get; set; }

        [XmlElement("Win")]
        public Win[] Win { get; set; }
    }

    public class Win
    {
        public string Kiss { get; set; }
    }
}