本文介绍了ASP.NET MVC FileStreamResult 未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,我从任何非必要的行中删除了这些代码,以保留最小的可重现情况.我期望它返回图像,但它没有.据我所知,它返回一个空文件:

I have the following code which I stripped out of any non-essential lines to leave the minimun reproducable case. What I expect is for it to return the image, but it doesn't. As far as I can see it returns an empty file:

public ActionResult Thumbnail(int id) {
    var question = GetQuestion(db, id);
    var image = new Bitmap(question.ImageFullPath);
    MemoryStream stream = new MemoryStream();
    image.Save(stream, ImageFormat.Jpeg);
    return new FileStreamResult(stream, "image/jpeg");
}

你能找出这段代码有什么问题吗?在调试器中,我可以看到流的大小在增长,因此它似乎正在获取数据,尽管我无法验证它是正确的数据.我不知道如何调试 FileStreamResult 本身.

Can you identify what's wrong with this code? In the debugger I can see that the stream grows in size so it seems to be getting the data although I haven't been able to verify it's the correct data. I have no idea how to debug the FileStreamResult itself.

推荐答案

需要插入

stream.Seek(0, SeekOrigin.Begin);

调用后

Image.Save()

这会将流倒回到已保存图像的开头.否则,流将位于流的末尾,并且不会向接收器发送任何内容.

This will rewind the stream to the beginning of the saved image. Otherwise the stream will be positioned at the end of the stream and nothing is sent to the receiver.

这篇关于ASP.NET MVC FileStreamResult 未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 16:41