简体   繁体   中英

C# WEB-API and how to post xml as List

My C# web api:

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

and I try to test POST as XML

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

but I am getting back

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

You are sending an object of type "AgadoFreeWork" in your example, but your endpoint expects a list holding items of this type. As well I would define an array of type "AgadoFreeWork" for this endpoint, there is probably no need to use a List. Have a look at this post Posting array of objects with MVC Web API

You are missing namespace in the POST XML that you are sending. Add the namespace to your XML and it should work.

Like below:

 <?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">

Also, you should be sending an array of AgadoFreeWork. Some thing like,

<?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>

If you don't want to send namespaces with the XML that you are sending, refer here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM