c# - 是否可以在 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();
}
}
解决方案
你不能以编程方式做到这一点。请求长度由 HttpWorkerRequest 在调用实际 HttpHandler 之前处理。这意味着在请求到达服务器并由相应的 asp.net worker 处理后执行通用处理程序或页面。
您无法控制页面代码或 HttpHandler 中的 maxRequestLength!
如果您需要为特定页面设置最大长度,您可以使用标签按如下方式执行:
<configuration>
<location path="yourPage.aspx">
<system.web>
<httpRuntime maxRequestLength="2048576" executionTimeout="54000" />
</system.web>
</location>
</configuration>
推荐阅读
- angular - 与依赖于 API 数据的 DOM 操作相关的问题
- javascript - 如何在 contenteditable div 中用 span 包围用户输入?
- snowflake-cloud-data-platform - 使用自动摄取 Snowpipes 时,是否有消除重复记录的最佳做法?
- python - 使用 google colab 同时更改代码中的相同单词
- java - 使用 JSOUP 登录 Github
- node-red - 节点红色仪表板未使用模板自动更新
- c# - 将 Visual Studio 2019 从 16.9.7 更新到 16.10.2 后出现 .NET UWP XamlParseException 错误
- reinforcement-learning - 使用 RLlib 时,如何防止我在评估运行期间收到的奖励总和间隔重复?
- html - Angular 11 - 带滑轨的侧窗开口
- javascript - 简化javascript中的嵌套if else语句