C# WEB-API 以及如何将 XML 发布为 List

  • 本文关键字:XML List WEB-API c# rest
  • 更新时间 :
  • 英文 :


My C# web api:

[HttpPost]
[Route("freeworks")]
public IHttpActionResult Post([FromBody]List<AgadoFreeWork> value)
{

我尝试将 POST 作为 XML 进行测试

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AgadoFreeWork>
    <IsPublished>true</IsPublished>
    ....

但我回来了

{
Message: "The request is invalid."
ModelState: {
value: [1]
0:  "Error in line 1 position 23. Expecting element 'ArrayOfAgadoFreeWork' from namespace 'http://schemas.datacontract.org/2004/07/Agado.Restful.Classes'.. Encountered 'Element' with name 'ArrayOfAgadoFreeWork', namespace ''. "
-
}-
}

在示例中,您正在发送类型为"AgadoFreeWork"的对象,但您的终端节点需要一个包含此类型项目的列表。同样,我会为这个端点定义一个类型为"AgadoFreeWork"的数组,可能不需要使用列表。看看这篇文章 使用 MVC Web API 发布对象数组

您正在发送的 POST XML 中缺少namespace。 将命名空间添加到 XML,它应该可以工作。

如下所示:

 <?xml version="1.0" encoding="UTF-8"?>
        <ArrayOfAgadoFreeWork xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:xsd="http://www.w3.org/2001/XMLSchema">

另外,你应该发送一个数组的AgadoFreeWork。像这样的事情,

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ArrayOfAgadoFreeWork xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <AgadoFreeWork>
      <IsPublished>true</IsPublished>
  </AgadoFreeWork>
</ArrayOfAgadoFreeWork>

如果您不想使用要发送的 XML 发送命名空间,请参阅此处

最新更新