我有一个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)
有没有人测试过这种基于流的文件返回控制器?你是怎么成功的?我应该干脆不处理我的课程吗?真的吗?