首页 > 解决方案 > 是否可以在 web.config 中不添加 maxRequestLength 的情况下流式上传大文件?

问题描述

 ┌─────────┐      ┌─ ───────────┐      ┌───────────────────────┐
 │ Postman │ ───► │ Web API App │ ───► │ Save file to a folder │
 └─────────┘      └─────────────┘      └───────────────────────┘

为了模拟,我通过邮递员将文件流式传输到 Web API,API 最终将文件保存到文件夹中。

问题-input.Read抛出Maximum request length exceeded.异常。

问题- 我可以在 web.config 中不添加maxRequestLength 和 maxAllowedContentLength的情况下流式上传大文件吗?

换句话说,我们是否有任何解决方法而不添加这些设置web.config

在此处输入图像描述

public class ServerController : ApiController
{
    public async Task<IHttpActionResult> Post()
    {
        // Hard-coded filename for testing
        string filePath = string.Format(@"C:\temp\{0:yyyy-MMM-dd_hh-mm-ss}.zip", DateTime.Now);

        int bufferSize = 4096;
        int bytesRead;
        byte[] buffer = new byte[bufferSize];

        using (Stream input = await Request.Content.ReadAsStreamAsync())
        using (Stream output = File.OpenWrite(filePath))
        {
            while ((bytesRead = input.Read(buffer, 0, bufferSize)) > 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }

        return Ok();
    }
}

标签: c#asp.netasp.net-web-api

解决方案


你不能以编程方式做到这一点。请求长度由 HttpWorkerRequest 在调用实际 HttpHandler 之前处理。这意味着在请求到达服务器并由相应的 asp.net worker 处理后执行通用处理程序或页面。

您无法控制页面代码或 HttpHandler 中的 maxRequestLength!

如果您需要为特定页面设置最大长度,您可以使用标签按如下方式执行:

<configuration>
  <location path="yourPage.aspx">
    <system.web>
      <httpRuntime maxRequestLength="2048576" executionTimeout="54000" />
    </system.web>
  </location>
</configuration>

推荐阅读