Request.Content.ReadAsMultipartAsync()和OutOfMemory异常

3
我将使用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>

但我仍然会收到这个异常。异常的结构如下:
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
请确保虚拟目录(如下面的示例中的“~/uploads”目录)在物理上存在,这是上传图像文件的第一步。
string uploadPath = HttpContext.Current.Server.MapPath("~/uploads");

MyStreamProvider streamProvider = new MyStreamProvider(uploadPath);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接