我正在尝试从MVC控制器下载大文件 OutOfMemoryException
。我想减少对服务器内存的需求,那么如何在不先缓冲其全部内容的情况下下载文件呢?
我的代码是:
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
var stream = new MemoryStream();
ExportService service = new ExportService(_mapper, Repository);
service.ExportVersion(view.ExportType, version, products, regions,
indicators, periods, stream);
stream.Position = 0;
return File(stream, "text/plain");
我希望在创建内容时将内容流式传输到浏览器。为了尝试实现这一点,我将Response.OutputStream
传递给服务并写信给MemoryStream
而不是OutOfMemoryException
。但是,这会创建相同的Response.BufferOutput = false
,因为默认情况下,ASP.NET会在将所有内容发送到浏览器之前对其进行缓冲。即使我设置EmptyResult
(并返回OutOfMemoryException
),我仍然会得到Response.BufferOutput = false;
ExportService service = new ExportService(_mapper, Repository);
service.ExportVersion(view.ExportType, version, products, regions,
indicators, periods, Response.OutputStream);
return new EmptyResult();
。
[OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
System.Collections.Generic.List`1.set_Capacity(Int32 value) +62
System.Collections.Generic.List`1.EnsureCapacity(Int32 min) +43
System.Collections.Generic.List`1.Add(T item) +51
MyApp.Mapping.DocumentVersionEntityConverter.LoadMultiVariableData(DocumentVersion version, MultiVariableQuestionView view) in c:\svn\Client Applications\MyApp\Web\Config\Mapping\DocumentVersionEntityConverter.cs:207
MyApp.Mapping.DocumentVersionEntityConverter.SetResponses(DocumentVersion version, List`1 questions, DataFilters filters) in c:\svn\Client Applications\MyApp\Web\Config\Mapping\DocumentVersionEntityConverter.cs:112
MyApp.Mapping.DocumentVersionEntityConverter.ScanSection(DocumentVersion version, SectionView section, DataFilters filters) in c:\svn\Client Applications\MyApp\Web\Config\Mapping\DocumentVersionEntityConverter.cs:79
MyApp.Mapping.DocumentVersionEntityConverter.Convert(ResolutionContext context) in c:\svn\Client Applications\MyApp\Web\Config\Mapping\DocumentVersionEntityConverter.cs:63
AutoMapper.DeferredInstantiatedConverter`2.Convert(ResolutionContext context) +57
AutoMapper.<>c__DisplayClass15.<ConvertUsing>b__14(ResolutionContext context) +10
AutoMapper.Mappers.CustomMapperStrategy.Map(ResolutionContext context, IMappingEngineRunner mapper) +13
AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context, IMappingEngineRunner mapper) +130
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) +355
更新
我确信此问题 是由于达到了可用内存的限制,因为代码在一台计算机上运行,而在另一台计算机上运行。此外,在具有更多受限内存的机器上,strack跟踪显示错误发生在代码中的可变位置,具体取决于下载的内容。下面是一个示例堆栈跟踪,它显示了在为List对象分配内存时发生的异常:
app/etc/modules