Skip to main content
 首页 » 编程设计

c#之是否可以在不在 web.config 中添加 maxRequestLength 的情况下流式上传大文件

2024年02月25日39yxwkf

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

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

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

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

换句话说,如果不在 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(); 
    } 
} 

请您参考如下方法:

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

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

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

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