c# - Request.Content.ReadAsMultipartAsync() 和 OutOfMemory 异常

标签 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>

但我仍然得到这个异常。异常具有以下结构:

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 上传大文件呢?

最佳答案

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

string uploadPath = HttpContext.Current.Server.MapPath("~/uploads");

MyStreamProvider streamProvider = new MyStreamProvider(uploadPath);

关于c# - Request.Content.ReadAsMultipartAsync() 和 OutOfMemory 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41223185/

相关文章:

c# - 如何获取包含 Excel 数据的列数

c# - 双击可编辑的 TreeViewItem

c# - 如何获取最后一个错误(WSAGetLastError)?

c# - 使用模态框时出现问题

c# - 我的 CollectionViewSource 没有获取更改

c# - Server.Transfer() 与。服务器.执行()

asp.net - AjaxExtender控制工具套件在dotnetnuke中不起作用

c# - Entity Framework 7 与 ASP.NET 4.6

javascript - 带有单个字符串参数的 WebApi 2 POST 不起作用

rest - 如何实现一个显示 ASP.NET Web API OData 服务可用的所有方法的页面?