I have not been able to get model binding to work when doing a POST using XML data with ASP.NET Web API. JSON data works fine.
Using a brand new Web API project, here are my model classes:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PostResponse
{
public string ResponseText { get; set; }
}
Here is my post method in the controller:
public PostResponse Post([FromBody]Person aPerson)
{
var responseObj = new PostResponse();
if (aPerson == null)
{
responseObj.ResponseText = "aPerson is null";
return responseObj;
}
if (aPerson.FirstName == null)
{
responseObj.ResponseText = "First Name is null";
return responseObj;
}
responseObj.ResponseText = string.Format("The first name is {0}", aPerson.FirstName);
return responseObj;
}
I am able to run it successfully with JSON from Fiddler:
Request Headers:
User-Agent: Fiddler
Host: localhost:49188
Content-Type: application/json; charset=utf-8
Content-Length: 38Request Body:
{"FirstName":"Tom","LastName":"Jones"}Result:
{"ResponseText":"The first name is Tom"}
When passing in XML, the Person object is not hydrated correctly:
Request Headers:
User-Agent: Fiddler
Host: localhost:49188
Content-Type: text/xml
Content-Length: 79Request Body:
<Person>
<FirstName>Tom</FirstName>
<LastName>Jones</LastName>
</Person>Result:
<ResponseText>aPerson is null</ResponseText>
From what I understand XML should work similar to JSON. Any suggestions on what I’m missing here?
Thanks,
Skip