Thursday, 6 March 2014

Posting XML to the WebAPI passes a NULL input parameter

The default implementation of WebApi has a method that accepts a single value via the POST method:

public void PostData([FromBody]string value)
{
    Debug.WriteLine(value);
}

And this works fine with JSON. But what if you want to send a simple XML document?

<InputData><Data>Hello</Data></InputData>

If you pass this as application/xml the method is called, but the value comes through as null. There are various behaviours at work here. The serializer tries to serialize to classes. So really a POCO should be created like follows:

public class InputData
{
    public string Data { get; set; }
}

And the controller modified to take the class:

public void Post([FromBody]InputData xml)
{
    Debug.WriteLine(xml);
}

Yet still POSTing this to the Web API still returns null. The second behaviour is that by default the namespaces are expected. So only this works:
<InputData 
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://schemas.datacontract.org/2004/07/NewBusiness.WebApi.Controllers">
    <Data>Hello</Data>
</InputData>

Unless you allow the XML serializer in WebApiConfig:

config.Formatters.XmlFormatter.UseXmlSerializer = true;

And then this works:

<InputData><Data>Hello</Data></InputData>

To get it to serialize to a string, e.g.

public void PostData([FromBody]string value)
{
    Debug.WriteLine(value);
}

then you would need to change the serializer.

3 comments:

  1. Thanks a lot....it was big help for me...working fine and I know from you why :)

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. I think it would be good to point out that in your post call to the API controller, the header's content type should be "text/html".

    ReplyDelete