.NET 4.5.2 ASP.NET API上传大文件遇413错误求助
解决ASP.NET API 4.5.2上传大文件(10MB)报413错误的方案
1. 补全web.config核心请求长度配置
确保覆盖所有相关节点,注意单位差异:
- system.web节点:
maxRequestLength单位为KB,10MB需设为10240以上,同时配置超时避免中断:
<system.web> <httpRuntime targetFramework="4.5.2" maxRequestLength="13312" executionTimeout="3600" /> </system.web>
(注:10MB图片转base64后体积约增33%,设为13312KB对应13MB,预留冗余)
- system.webServer节点:
maxAllowedContentLength单位为字节,需匹配base64后的体积:
<system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="13631488" /> </requestFiltering> </security> </system.webServer>
2. 完善WebHttpBinding的全链路配置
针对WCF Web API,仅设置maxReceivedMessageSize不够,需同步配置缓冲和读取配额:
<system.serviceModel> <bindings> <webHttpBinding> <binding name="LargeFileBinding" maxReceivedMessageSize="13631488" maxBufferSize="13631488" maxBufferPoolSize="13631488"> <readerQuotas maxDepth="32" maxStringContentLength="13631488" maxArrayLength="13631488" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> </binding> </webHttpBinding> </bindings> <services> <service name="YourApiServiceNamespace.YourApiService"> <endpoint address="" binding="webHttpBinding" bindingConfiguration="LargeFileBinding" contract="YourApiServiceNamespace.IYourApiContract" behaviorConfiguration="WebHttpBehavior" /> </service> </services> </system.serviceModel>
重点:确保绑定配置已关联到实际的API端点,readerQuotas的字符串和数组长度必须覆盖base64后的体积。
3. 站点级UploadReadAheadSize调整
Windows Server 2012 R2 IIS中,需针对当前站点而非全局配置:
- 打开IIS管理器,选中目标站点 → 右键选择「配置编辑器」
- 选择
system.webServer/serverRuntime节点 - 将
uploadReadAheadSize设为13631488(13MB),HTTPS站点建议翻倍至27262976,避免IIS提前截断请求
4. 排查URL Rewrite模块限制
若站点启用了URL Rewrite,检查规则是否隐含请求大小限制:
- 打开IIS管理器 → 站点 → URL Rewrite → 逐一检查规则
- 若有自定义规则,添加请求长度允许配置:
<rewrite> <rules> <rule name="YourExistingRule"> <match url="..." /> <action type="..." /> <requestLimits maxAllowedContentLength="13631488" /> </rule> </rules> </rewrite>
5. 修正模型字段长度限制
检查API接收模型的字符串字段,避免数据注解限制长度:
public class ImageUploadRequest { // 移除或调整MaxLength/StringLength的限制值 [MaxLength(13631488)] public string Base64ImageContent { get; set; } // 其他业务字段 }
6. 应用程序池参数优化
- 打开IIS管理器 → 应用程序池 → 选中对应池 → 高级设置
- 将「队列长度」调整为1000,「进程模型/空闲超时」设为30分钟
- 关闭「回收/固定时间间隔」,避免上传过程中应用池意外回收
内容的提问来源于stack exchange,提问作者scott lafoy
相关产品推荐
相关产品推荐

