Efficiently forward content from internal HttpClient call in ASP.NET Core

.net-core, asp.net-core, c#, dotnet-httpclient

Solution

You can just return the `Stream` from the action and ASP.NET Core MVC will efficiently write it to the response body.

[HttpPost]
public async Task<Stream> Post([FromBody]SearchQuery searchQuery)
{
    var response = await _searchClient.Search(searchQuery);
    return await response.ReadAsStreamAsync();
} 

Problem

I'm calling an internal HTTP service from my ASP.NET Core app. The response messages from this service can be very large, so I want to forward them as efficiently as possible. If possible I just want to "map" the content to the controller response - or in other words "pipe the stream comming from the service to the stream going out of my controller". My controller method so far simply calls the service: ``` [HttpPost] public Post([FromBody]SearchQuery searchQuery) { var response = _searchClient.Search(searchQuery); // ? } ``` The service is called by an HttpClient instance. Here (as an example) I just return the HttpContent, but of course I could return the completely read and serialised body (which I obviously don't want): ``` public async Task<HttpContent> Search(SearchQuery searchQuery) { var content = new StringContent(TsearchQuery, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync("_search", content); return response.Content; } ``` Is it efficient and fast to return the content? How would I pass the content in my controller method to the response? Does ASP.NET Core create streams underneath? Or should I handle streams in my code explicitly?

Original source

Related problems