无法从 ASP.NET MVC 中的操作 return 图像流

Unable to return image stream from action in ASP.NET MVC

我有以下操作:

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

我有一个通用的持久性策略(使用 Amazon S3)检索 StaticImage 如下:

//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 包含图像的内容:

它正在被很好地复制到新流中(参见 Length):

但是,0 字节从我的控制器返回:

如果您查看第二张图片,流的位置是 197397。我的假设是,当您将它传递给 FileStreamResult 的构造函数时,它不会复制它,因为该位置位于流的末尾。在将其传递给 FileStreamResult 的构造函数之前,将位置设置回 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();