Reputation: 26281
I have the following action:
public async Task<ActionResult> Get(string path)
{
StaticImage image = await _images.UseRepositoryAsync(repo => repo.ReadAsync(path));
return image != null ? new FileStreamResult(image.Stream, "image/jpeg") : (ActionResult)HttpNotFound();
}
I have a generic persistence strategy (uses Amazon S3) that retrieves StaticImage
as follows:
//E is StaticImage in this case
//The returned entity is not disposed, it leaves that responsability to the controller
//However, the response IS disposed, that's why I need to copy the stream
public async Task<E> SelectAsync(params object[] keys)
{
using(GetObjectResponse response = await MakeGetObjectRequestAsync(keys.First().ToString()))
{
if(response == null) return default(E);
E entity = CreateEntity();
entity.Key = response.Key;
Stream entityStream = new MemoryStream(Convert.ToInt32(response.ResponseStream.Length));
await response.ResponseStream.CopyToAsync(entityStream);
entity.Stream = entityStream;
return entity;
}
}
response.ResponseStream
contains the image's content:
And it is being copied just fine to the new stream (see Length
):
However, 0
bytes are returned from my controller:
Upvotes: 1
Views: 1232
Reputation: 21887
If you look at your second image, the stream's position is 197397
. My assumption is that when you're passing it to the constructor of FileStreamResult
, it's not copying it because the position is at the end of the stream. Before you pass it to the constructor of FileStreamResult
, set the position back to 0:
StaticImage image = await _images.UseRepositoryAsync(repo => repo.ReadAsync(path));
image.Stream.Position = 0;
return image != null ? new FileStreamResult(image.Stream, "image/jpeg") : (ActionResult)HttpNotFound();
Upvotes: 4