[FromBody]. Param value in Post Controller is always NULL

178 views Asked by At

I am new to .net web apps. My usecase is make a post call with XML as body. I am trying to make a call through postman, but the param value received in my controller is always null. Below are the thing I have:

He is my XML body:

  <?xml version="1.0" encoding="utf-8"?>
  <document>
    <id>123456</id>
    <content>This is document that I posted...</content>
    <author>Michał Białecki</author>
    <links>
      <link>2345</link>
      <link>5678</link>
    </links>
  </document>

Here is the DTO object I am using:

[XmlRoot(ElementName = "document", Namespace = "")]
public class ABC
{
    [XmlElement(DataType = "string", ElementName = "id")]
    public string Id { get; set; }

    [XmlElement(DataType = "string", ElementName = "content")]
    public string Content { get; set; }

    [XmlElement(DataType = "string", ElementName = "author")]
    public string Author { get; set; }

    [XmlElement(ElementName = "links")]
    public LinkDto Links { get; set; }
}

public class LinkDto
{
    [XmlElement(ElementName = "link")]
    public string[] Link { get; set; }
}

Apart from this, I have also added this in my Startup.cs services.AddMvc().AddXmlDataContractSerializerFormatters();

And at last this is my controller:

[Route("api/[controller]")]
public class UploadFileController : ControllerBase
{
    [HttpPost]
    [Route("upload")]
    public void RegisterDocument([FromBody] Document dto)
    {
        Console.WriteLine("Inside the controller");
    }
}

This is how I am calling it from postman: enter image description here

One other thing I noticed while in debugging mode is I am seeing these errors as well: enter image description here

Can someone please help? I have tried various solutions but not able to make it work. Thanks in advance.

1

There are 1 answers

1
Rena On BEST ANSWER

You need add AddXmlSerializerFormatters():

services.AddMvc()
    .AddXmlSerializerFormatters()
    .AddXmlDataContractSerializerFormatters();

Your xml should like below(remove <?xml version="1.0" encoding="utf-8"?>):

<document>
    <id>123456</id>
    <content>This is document that I posted...</content>
    <author>Michał Białecki</author>
    <links>
      <link>2345</link>
      <link>5678</link>
    </links>
</document>

Your Action need to change Document to ABC :

[HttpPost]
public void Post([FromBody] ABC dto)
{
}

Result: enter image description here