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
Add this in your WebApiConfig.cs
:
config.Formatters.XmlFormatter.UseXmlSerializer = true;
This forced Web API to use XMLSerializer instead of DataContractSerializer and allows you to pass raw XML.
Otherwise you have to pass fully qualify datacontract XML i.e.:
<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Test.WebAPI.Controllers">
<FirstName>a</FirstName>
<LastName>b</LastName>
</Person>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With