Accepting application/xml content in webapi controller

1.3k Views Asked by At

I want to create an action that will accept application/xml content.

Basically I have created this so far.

namespace App.Areas.Test.Controllers
{

    public class UserModel
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }


    public class TestController : ApiController
    {
        [HttpPost]
        public UserModel Test([FromBody] UserModel um)
        {
            return um;
        }
    }
}

When I post the following content

    <?xml version="1.0" encoding="UTF-8" ?>
    <UserModel>
    <FirstName>Some Name</FirstName>
    <LastName>Some Last Name</LastName>
    <Age>30</Age>
    </UserModel>

I end up with this response

<UserModel i:nil="true" />

I tried removing FromBody attribute, but that did not help either. For some reason content is not binding to the existing model.

2

There are 2 best solutions below

0
On BEST ANSWER

this will do the trick...

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;
1
On

Did you add the Content-Type : application\xml header? You need to inform the serialiser what format the body is in.