1

I'm trying to use a DelegatingHandler to wrap my Web API responses. I'm using this as an example.

At some point the content needs to be read from the response object:

if (response.TryGetContentValue(out content) && ...)

The solution didn't work because response.TryGetContentValue(out content) doesn't actually return anything (or populate the content variable that is).

However if I 'change' the code to...

response.Content.ReadAsAsync<object>().Result;

... it does work.

I would expect that TryGetContentValue and Content.ReadAsAsync return the same value. Why is this not the case?

EDIT:

enter image description here

Ropstah
  • 17,538
  • 24
  • 120
  • 194

1 Answers1

3

If you look at the source code of HttpResponseMessageExtensions.TryGetContentValue method you will see something like:

ObjectContent content = response.Content as ObjectContent;
if (content != null)
{
     ...
}

value = default(T);
return false;

It means that this method assumes that HttpResponseMessage.Content property will return an instance of ObjectContent type. However, in your case it is StringContent and it cannot be casted to ObjectContent.

Michał Komorowski
  • 6,198
  • 1
  • 20
  • 24
  • I did look at the source code, somehow I assumed `ObjectContent` as being castable to `StringContent`... Thanks! – Ropstah Aug 08 '16 at 10:01