asp.net-web-apiasp.net-web-api2frombodyattribute

Accepting application/xml content in webapi controller


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.


Solution

  • this will do the trick...

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