2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That was definitely it - I missed some ILists in the object hierarchy, but providing the right implementation type made the XmlSerializer happy. That behavior totally makes sense, just had no idea that's how it was handled. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.