当从MemoryStream返回时,ASP.net MVC ActionResult破坏了excel文件

我有我的控制器内的以下行动

public ActionResult DownloadExcel() { //create and populate Excel file here C1XLBook testBook = new C1XLBook(); //populate it here MemoryStream ms = new MemoryStream(); testBook.Save(ms, FileFormat.Biff8); return File(ms, "application/ms-excel", "test-file.xls"); } 

当打开文件时,我得到Excel消息说文件与扩展名不匹配,文件打开损坏。

如果我将文件保存在硬盘上,并从那里返回,一切都很好:

 return base.File(@"C:\LOGS\test-file.xls", "application/ms-excel", "test-excel.xls"); 

我最初认为Save函数在将它保存到MemoryStream中时会损坏它,所以我保存并重新加载它,并且很好地传回给用户 – 当保存在Hard Drive上并从那里返回时,而不是从的MemoryStream

有任何想法吗? 我不太喜欢将文件保存在硬盘驱动器….除此之外,我应该能够将它保存到MemoryStream并从那里返回?

我有一个预感是可能不应该使用MemoryStream在MVC中返回文件,因为每个请求都是孤立的?

也许你需要回滚的内存stream(设置ms.Position = 0; )之前传递给结果? 呼吁Save其立场后,将在年底,而不是开始。