Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 356
Knack Avatar asked May 07 '17 11:05

Knack


2 Answers

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.

like image 165
Leon Avatar answered Oct 20 '22 00:10

Leon


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();
} 
like image 45
davidfowl Avatar answered Oct 19 '22 22:10

davidfowl