I’m leveraging the new MVC4 ApiController to build out a search interface; something like this:
public IEnumerable<RecordSummaryType> Get( ... )
{
var list = MyService.GiveMeTheList( ... );
return list;
}
public SingleRecordDetailType Get(long id)
{
var result = MyService.GiveMeASingleValue(id);
return result;
}
For some reason, in this case the IEnumerable call honors content negotiation – i.e., when I pass application/xml in the request accept headers it returns XML, and when I pass application/json it returns JSON – but the SingleRecordType call only returns JSON, even if you ask for XML.
So my question is – are there differences in the way MVC 4 handles collections over single value types? Or, more likely, are there hooks in MVC where one can inadvertently disable content negotiation for certain calls?
It depends whether the SingleRecordDetailType can be serialized by the XmlSerializer. The XmlSerializer is default XML formatter in ASP.NET Web API, read here to know more about its limitations.
If Web API can’t serialize the response with the requested formatter it will use the first formatter in the list which is capable of serializing the response (most of time this is JSON formatter).
As a solution you can modify yoru class to be serializable by XmlSerializer or reconfigure the XML formatter to use data contract serializer by setting the UseDataContractSerialzier property to true.