【问题标题】:Unable to return image stream from action in ASP.NET MVC无法从 ASP.NET MVC 中的操作返回图像流
【发布时间】:2015-09-17 16:28:01
【问题描述】:

我有以下操作:

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 字节从我的控制器返回:

【问题讨论】:

    标签: c# .net asp.net-mvc amazon-s3 stream


    【解决方案1】:

    如果您查看第二张图片,则流的位置是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();
    

    【讨论】:

    • 谢谢!我不敢相信这是问题所在! :P
    • @MatiCicero 没问题。这是使用流时的常见问题。
    猜你喜欢
    • 1970-01-01
    • 2013-09-11
    • 2015-12-19
    • 2013-06-12
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 2014-06-25
    相关资源
    最近更新 更多