【问题标题】:C# WEB-API and how to post xml as ListC# WEB-API 以及如何将 xml 作为列表发布
【发布时间】:2015-04-13 08:38:03
【问题描述】:

我的 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 ''. "
-
}-
}

【问题讨论】:

  • 问题是……?

标签: c# rest


【解决方案1】:

在您的示例中,您正在发送“AgadoFreeWork”类型的对象,但您的端点需要一个包含此类型项目的列表。我也会为此端点定义一个“AgadoFreeWork”类型的数组,可能不需要使用列表。看看这个帖子Posting array of objects with MVC Web API

【讨论】:

    【解决方案2】:

    您在发送的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 发送命名空间,请参考 here

    【讨论】:

    • 感谢您的回答。我已经用 试过了,但还是一样,还是一样的消息
    • @senzacionale:你试过我提到的命名空间吗?查看我的更新答案..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多