FilePathResult使用大文件抛出OutOfMemoryException

时间:2013-11-29 09:43:31

标签: c# asp.net-mvc

我在我的控制器中有这个Action,它将一个文件返回给用户。

public virtual ActionResult ReturnFile(string fileName, string filePath, string contentType)
{
    var cd = new System.Net.Mime.ContentDisposition
    {
        FileName = fileName,

        // always prompt the user for downloading, set to true if you want 
        // the browser to try to show the file inline
        Inline = false,
    };

    // set token for close the modal-window
    CookiesHelper.SetValueDownloadTokenInCookie();
    Response.AppendHeader("Content-Disposition", cd.ToString());
    return File(filePath, contentType);
}

它工作正常,但问题是当文件很大(略大于220 Mb)时,它会抛出OutOfMemoryException

这是堆栈跟踪

[OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
   System.IO.MemoryStream.set_Capacity(Int32 value) +93
   System.IO.MemoryStream.EnsureCapacity(Int32 value) +64
   System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) +330
   Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.ArteryFilter.Write(Byte[] buffer, Int32 offset, Int32 count) +106
   System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +9509748
   System.Web.HttpResponse.FilterOutput() +104
   System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +49
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69

有什么想法吗?

2 个答案:

答案 0 :(得分:9)

这是因为您的请求正在使用PageInspector,如堆栈跟踪的这一行所示:

  

Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.ArteryFilter.Write(Byte [] buffer,Int32 offset,Int32 count)+106

要解决此问题,请取消选中Visual Studio中的浏览器复选框,如以下屏幕截图所示:

Uncheck Browser Link

答案 1 :(得分:0)

我认为您可以通过在Web.config文件中设置maxQueryString来解决问题。如果您尚未进行设置,请查看以下代码:

 <system.webServer>
   <security>
      <requestFiltering>
        <requestLimits maxUrl="10999" maxQueryString="9999" />
      </requestFiltering>
    </security>
 </system.webServer>

您可以根据需要设置最大值。