Home > Blockchain >  How to pass on a FileStreamResult from another controller
How to pass on a FileStreamResult from another controller

Time:09-06

I have an ASP.Net Core controller that returns a FileStreamResult:

[HttpGet("{imageCode}")]
public async Task<IActionResult> ShowMeYourBytes(string imageCode)
{
    var result = await _imageService.GetMyImage(imageCode);
    return new FileStreamResult(result.Stream, result.MimeType);
}

Now, in another ASP.Net Core controller, running somewhere else, I want to do this:

[HttpGet("{imageCode}")]
public async Task<IActionResult> ByteSizedImage(string imageCode)
{
    var request = new HttpRequestMessage(HttpMethod.Get, $"urlToServer/api/{imageCode}");
    var httpClient = new HttpClient();
    var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);

    return new FileStreamResult(response.Content.ReadAsStream(cancellationToken), response.Content.Headers.GetValues("Content-Type").First())
}

I expected this to work:

<img src="blabla.com/ByteSizedImage/mycoolimage" /> 

But this doesn't work, the image refuses to load. Looking at the response in ByteSizedImage in the debugger, I see the response data, so I'm receiving it. So the error is in how I'm passing it on from the ByteSizedImage method. How do I get ByteSizedImage to act as a "proxy" for my FileStreamResult?

CodePudding user response:

Turns out I was overthinking it. The proxy controller can just directly return the stream. That stream is a FileStreamResult already. You don't need to wrap it in another FileStreamResult. See this code:

[HttpGet("{imageCode}")]
public async Task<IActionResult> ByteSizedImage(string imageCode)
{
    var request = new HttpRequestMessage(HttpMethod.Get, $"urlToServer/api/{imageCode}");
    var httpClient = new HttpClient();
    var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);

    return Ok(response.Content.ReadAsStream(cancellationToken));
}
  • Related