Knack
Knack

Reputation: 1124

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

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?

Upvotes: 12

Views: 4578

Answers (2)

Leon
Leon

Reputation: 149

From my experience, passing through the response stream as David suggested works, but does not maintain the HTTP status code. You'd have to add this line:

Response.StatusCode = (int)response.StatusCode;

This answer provides an alternative way of copying a complete HttpResponseMessage.

Upvotes: 4

davidfowl
davidfowl

Reputation: 38804

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();
} 

Upvotes: 16

Related Questions