Net8 大文件上传--服务器请求超时--解决方案

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

其实吧,随着AI的发展,上面两句话中的第二句基本没啥用了,人的脑力和AI无法比,AI相当于集成了全人类的知识精华

一转眼,2026了,12年毕业的我,在IT行业摸爬滚打也来到了第14个年头,今年也是本命年,36岁了,虽说度过了35岁危机,但也不知道还能在这一行干多久。衷心祝愿公司事业蒸蒸日上,能够上市,也为自己这位公司前5员工争取点股份,哈哈哈,梦想还是要有的,万一实现了呢?💪

Net8文件上传核心要解决的是请求超时及大文件上传时内存溢出,针对这两点,做个简要说明

内存溢出的解决方案可通过切片式上传,将大文件切割为若干份,分片上传至服务器,最终通过校验算法完成合并,在此不作代码说明,网上一大堆

请求超时的问题:

1、Net8 webConfig文件的修改

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath=".\VOL.WebApi.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" requestTimeout="00:15:00" />
<security>
        <requestFiltering>
          <requestLimits maxAllowedContentLength="314572800" />
        </requestFiltering>
      </security>
 

    
    <httpProtocol>
      <customHeaders>
        <add name="Keep-Alive" value="timeout=600" />
      </customHeaders>
    </httpProtocol>
    </system.webServer>
  </location>
</configuration>
<!--ProjectGuid: 4db3c91b-93fe-4937-8b58-ddd3f57d4607-->

  简要说明如下:

requestTimeout="00:15:00"    是将IIS请求时长增加至15分钟

  

 <requestLimits maxAllowedContentLength="314572800" />   是将文件大小限制在300MB以下

  

   <add name="Keep-Alive" value="timeout=600" />  是指将HTTP请求链接保持在600秒

 2、startUp文件修改,增加如下配置(webconfig是300MB,这里是500MB,可以调整一样大)

   // 3. 配置表单选项(关键)
   services.Configure<FormOptions>(options =>
   { 
       options.ValueLengthLimit = int.MaxValue; // 单个值长度限制
       options.MultipartBodyLengthLimit = 500 * 1024 * 1024; // 500MB,多部分请求总长度
       options.MultipartBoundaryLengthLimit = int.MaxValue; // 边界长度限制
       options.MultipartHeadersCountLimit = int.MaxValue; // 头部数量限制
       options.MultipartHeadersLengthLimit = int.MaxValue; // 头部总长度限制
       options.BufferBodyLengthLimit = 500 * 1024 * 1024; // 缓冲体长度限制
       options.BufferBody = true; // 启用缓冲
       options.MemoryBufferThreshold = 1024 * 1024; // 1MB 后使用磁盘缓冲
   });

   // 4. 配置 IIS 限制(如果使用 IIS)
   services.Configure<IISServerOptions>(options =>
   {
       options.MaxRequestBodySize = 500 * 1024 * 1024; // 500MB
       options.AllowSynchronousIO = true; // 允许同步IO
   });

3、请求axios 请求时长调整(涉及到VUE 或 react)

axios.defaults.timeout = 250000;

 设置为250秒

  

最后,上传了一个260MB的文件,成功了!

posted @ 2026-01-14 10:20  天才卧龙  阅读(2)  评论(0)    收藏  举报