I can confirm that WebAPI does as you say and it looks for a formatter that
matches the Accept header ... To make things easier and consistent for
everyone I have abandoned the idea of returning plain text in some methods,
I will always return an XML serialised class no matter how small the data
might be. This is easier to document and the client will probably
appreciate it. So the confusion about choosing text or xml will go away.
I'll leave my text formatter there as a stub just in case someone wants csv
formatting or similar later.

I notice that if my controller method returns "string" then the xml
formatter sends back <String>hello</String> and Accept text/plain returns
"hello", which makes sense. If I try to get a class back as text it ignores
me and I get XML anyway, which also makes sense.

My task now is to remove the xmlns="" clutter from the xml root.

Part of my learners confusion is the large numbers of return types that are
possible from controller methods, some not even in the same class hierarchy.

Greg K



On 20 January 2014 14:31, David Burstin <david.burs...@gmail.com> wrote:

> Greg, let the web API deal with the formatting. Your controller should
> ideally just return an object which will be formatted according to the
> request.
>
> (apologies for brevity, I am playing mini golf with my son)
>
> Try it in Fiddler and you can see how changing the request will change the
> output. If you hard code the response type you are introducing unnecessary
> coupling snd potential future headaches.
>
> Sent from my flux capacitor. Please excuse brevity and any odd autocorrect
> errors.
> On 20/01/2014 1:54 PM, "Greg Keogh" <g...@mira.net> wrote:
>
>> Please ignore previous message as I hit Send instead of Save (bloody
>> Gmail interface!). Here's the correct message:
>>
>> Chaps, after some doodling around I see I can get the Accept values
>> straight out of the Request in the controller's code. That does now seem to
>> be the logical way of choosing the response format.
>>
>> More confusion though ... I tried to write a controller method that
>> returned either plain text or XML, but the samples I've found return
>> different types. Here are the two samples:
>>
>> public HttpActionResult Sample1()
>> return Ok("hello");
>>
>> public HttpResponseMessage Sample2()
>> return new HttpResponseMessage() { Content = new StringContent("hello") };
>>
>> The firsts returns <String>hello</String> and the second returns the
>> plain text "hello". But they're different return types and I can't figure
>> out how get one method to return Xml or text. Anyone know how. I'm still
>> searching.
>>
>> Greg K
>>
>

Reply via email to