Search code examples
c#asp.net-web-apidelegatinghandler

Wrapping WebApi responses using DelegatingHandler


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


Solution

  • 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.