Web API (.NET): POSTing an object in XML format to an ApiController

Problem: In a .NET Web API app, inside a class which extends ApiController, it is desirable to receive an object in both XML and JSON format, in the most transparent form possible. Receiving the whole XML as a string, or using attributes (.NET's annotations) in the class to serialize are not acceptable solutions.

What tends to happen is that the object is always set to null when calling the method. There are various possible solutions, among them adding an "=" at the beginning of the POST message body. But doing so is not optimal, because it's a .NET specific convention and would limit us (if a partner used an HTTP client made with C++ running on Linux, we'd be in trouble). We cannot receive a string directly because that would prevent us from receiving the object in JSON format.

Solution: Receive the object with the attribute (.NET annotation) [FromBody], and enable the xml serialization inside our controller. An ideal place to do so would be the class' static constructor. For instance:

public class SomeController : ApiController{

    //Static constructor
    static SomeController(){
        //Needed for xml deserialization to work
        var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
        xml.UseXmlSerializer = true;
    }

    public async Task<HttpResponseMessage>
    SomeMethodWhichReceivesBothXmlAndJson( [FromBody] SomeSerializableClass someInstance ){
        //...
    }

}

Comments

Popular posts from this blog

VB.NET: Raise base class events from a derived class

Apache Kafka - I - High level architecture and concepts

Upgrading Lodash from 3.x to 4.x