asp.net-web-apitransfer-encoding

Passing chunked third-party API response through a WebAPI controller


I am trying to consume an external API but the data that is returned is chunked:

Cache-control: max-age=7200
Content-Type: text/xml;charset=UTF-8
Vary: Accept-Encoding
P3P: CP="Anything"
ApacheTracking: localhost
Transfer-Encoding: chunked

which is causing me issues. I can see the data in Fiddler, but when trying to return the data from a Controller from within a WebAPI project, nothing is returned. My code looks like this:

// Try to get our products
using (var client = new HttpClient())
{
    var response = await client.GetAsync(signedUrl);

    return Ok(response);
}

but the client application has no data. It returns a statusCode of 200 though. Does anyone know how I can get my controller to return the chunked data?


Solution

  • You don't need to re-assemble the body, the HttpClient does this for you.

    You do need to read the response body though, because now you're trying to serialize an HttpResponseMessage, which it isn't really meant for.

    Depending on what you actually want to return to the client, introduce your own Data Transfer Object, or simply return a string:

    using (var client = new HttpClient())
    {
        var response = await client.GetAsync(signedUrl);
    
        var responseBody = await response.Content.ReadAsStringAsync();
    
        return Ok(responseBody);
    }
    

    Alternatively, if your API method has a return type of Task<HttpResponseMessage>, you could return the response of the API call directly (without wrapping it in Ok(), which will do the serialziation):

    return response;
    

    But I wouldn't do that, because you then can't control which header and body values your API will leak from the third-party API.