Request.Content.ReadAsMultipartAsync()和OutOfMemory Exception

时间:2016-12-19 13:00:44

标签: c# asp.net asp.net-web-api file-upload

我使用ASP.NET Web Api 2.2以下列方式上传文件:

[HttpPost]
public async Task<IHttpActionResult> Post()
{
    /* read the content */
    var contentTypeHeader = Request.Content.Headers.ContentType;
    var contentLength = Request.Content.Headers.ContentLength;

    /* Here I get the exception if the file is > 60/70 MB */
    var filesProvider = await Request.Content.ReadAsMultipartAsync();
    var fileContents = filesProvider.Contents.FirstOrDefault();
    var headers = fileContents.Headers;
    Stream fileStream = await fileContents.ReadAsStreamAsync();

    // ... code not related to this question
}

我已经设置了web.config,如下所示,以便接受最多1GB数据的文件:

  <system.web>
    <httpRuntime targetFramework="4.5" maxRequestLength="1048576" />
  </system.web>

  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
  </system.webServer>

但我仍然得到这个例外。 Exception具有以下结构:

An error occurred System.IO.IOException: Error writing MIME multipart body part to output stream. ---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
↵   at System.IO.MemoryStream.set_Capacity(Int32 value)
↵   at System.IO.MemoryStream.EnsureCapacity(Int32 value)
↵   at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
↵   at System.IO.MemoryStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)

所以,它看起来像.NET异常,而不是我的代码。但是,我如何使用MultiPart上传大文件?

1 个答案:

答案 0 :(得分:0)

确保首次上传图像文件的虚拟目录(“〜/ uploads”目录如下例所示)是物理存在的。

glm