0

我有一个Controller返回一个FileStreamResult通过SharpZipLib(我已经尝试过DotNetZip,没有区别)。

using (var buffer = new MemoryStream())
{
    using (var zipStream = new ZipOutputStream(buffer))
    {
        zipStream.PutNextEntry(new ZipEntry("The Simpsons"));
        var bart = Encoding.UTF8.GetBytes("Homer <3 donuts");
        zipStream.Write(bart, 0, bart.Length);
        zipStream.IsStreamOwner = false;    
        return File(buffer, MediaTypeNames.Application.Zip, fileName);
    }
}

我正在尝试对此进行单元测试:

var controller = new SimpsonsController();
var result = controller.ConfigurationReport(id);
Assert.IsInstanceOf<FileStreamResult>(result);

var streamResult = (FileStreamResult) result;
var zipInputStream = new ZipInputStream(streamResult.FileStream);

Assert.IsNotNull(zipInputStream);

var zipEntry = zipInputStream.GetNextEntry();
Assert.AreEqual("The Simpsons", zipEntry.Name);

现在单元测试失败了:

System.ObjectDisposedException : Cannot access a closed Stream.
   at System.IO.__Error.StreamIsClosed()
   at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputBuffer.Fill()
   at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputBuffer.ReadLeByte()
   at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputBuffer.ReadLeInt()
   at ICSharpCode.SharpZipLib.Zip.ZipInputStream.GetNextEntry()

如果我尝试通过浏览器直接下载具有类似堆栈跟踪的 IIS 500:

Cannot access a closed Stream.
System.ObjectDisposedException: Cannot access a closed Stream.
   at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.Web.Mvc.FileStreamResult.WriteFile(HttpResponseBase response)
   at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
   at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)

有没有人测试过这种基于流的文件返回控制器?你是怎么成功的?我应该干脆不处理我的课程吗?真的吗?

4

1 回答 1

3

试试这个,我认为你的问题是你正在处理正在返回的流。

public FileStreamResult PDF()
{
    MemoryStream buffer = new MemoryStream();
    using (var zipStream = new ZipOutputStream(buffer))
    {
        zipStream.PutNextEntry(new ZipEntry("The Simpsons"));
        var bart = Encoding.UTF8.GetBytes("Homer <3 donuts");
        zipStream.Write(bart, 0, bart.Length);
        zipStream.IsStreamOwner = false;
    }
    return File(buffer, MediaTypeNames.Application.Zip, fileName);
}

看看这个https://stackoverflow.com/a/10891136/985284并关注 Cheeso 的其他帖子以获取更多信息。

于 2012-08-10T09:23:58.877 回答